Skip to content

How to use aliases in a bash shell script

Aliases can be useful, on the Bash command line, but they are not enabled by default in non-interactice scripts.

Aliases can be used to avoid long command lines particularly if you pass the same set of arguments repeatedly, for example:

alias mycmd='podman run --env MYVARS_* --rm -it -v $PWD/.config:/myapp/.config myimage'

and then to use the alias on the CLI in a terminal window:

$ mycmd arg1 arg2 etc

I've been using aliases for many years, but it wasn't until today that I discovered that they didn't work in a non-interactive script.

test_alias.sh
#!/usr/bin/env bash

alias mycmd='podman run --env MYVARS_* --rm -it -v $PWD/.config:/myapp/.config myimage'
mycmd hello

and then running with:

chmod +x ./test_alias.sh
$ ./test_alias.sh
./test_alias.sh: line 4: mycmd: command not found

From the Bash Reference Manual alias expansion is disabled, by default, for non-interactive shells. It can be enabled by using the shopt builtin command:

test_alias.sh
#!/usr/bin/env bash

alias mycmd='podman run --env MYVARS_* --rm -it -v $PWD/.config:/myapp/.config myimage'
shopt -s expand_aliases # (1)
mycmd hello
  1. The-Shopt-Builtin

Of course, the Bash Reference Manual also says that functions are preferred over aliases for almost every purpose, which I probably would have been using if I had started writing the script