Alexander Zeitler

Alexander Zeitler

Using aliases in scripts with zsh

Published on Sunday, December 17, 2023

Photo by Ahmed Zayan on Unsplash

Using aliases

We often use shell aliases to make our life easier. However, when we try to use them in shell scripts (hence, subshells) it seems to get harder.

Let's say we have the following alias to run the AWS CLI in a docker container that is using the current directory as the working directory:

alias aws='docker run --rm -it -v ~/.aws:/root/.aws -v $(pwd):/aws amazon/aws-cli'

If we try to use this alias in a script, it will fail:

#!/bin/zsh

aws --profile my-aws-profile s3 cp s3://my-bucket/path/to/file .

This will result in the following error:

zsh: command not found: aws

There are a few things to know:

So, let's try to use a function instead of an alias:

#!/bin/zsh

aws() {
  docker run --rm -it -v ~/.aws:/root/.aws -v $(pwd):/aws amazon/aws-cli "$@"
}

Now we could add the function to our .zshrc and source it and try to use it in our script and get new errors.

Long story short, there's a file named ~/.zshenv (if it doesn't exist, just create it) that is sourced on every invocation of zsh. So, we can add the function to this file and it will be available in our scripts.

aws() {
  docker run --rm -it -v ~/.aws:/root/.aws -v $(pwd):/aws amazon/aws-cli "$@"
}

Now we can use the function in our script:

#!/bin/zsh

aws --profile my-aws-profile s3 cp s3://my-bucket/path/to/file .

And it will work as expected 🎉.

What are your thoughts about "Using aliases in scripts with zsh"?
Drop me a line - I'm looking forward to your feedback!
Imprint | Privacy