Bash: Use an alias in a variable

After some testing, I have concluded the following:

  • Aliases only work in interactive mode (add -i to the shebang).
  • Aliases are not evaluated when they come from an interpreted source (in this case, the variable.
  • You can get bash to use the alias with eval $1. Note that evaling anything created with a variable is dangerous, but since the whole point of the script requires arbitrary execution, I won't make too big a deal out of that.

From the bash man page:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).

So you could add shopt -s expand_aliases instead of -i.

Also,

Aliases are expanded when a command is read, not when it is executed.

Since variables are not expanded before the command is read, they will not be expanded further using the alias.


I had a similar problem and managed to solve my issue by turning my aliases to functions, as described on this site, which worked for me.

e.g.

alias lsd="ls -lash"

to

function lsd() { ls -lash; }

Tags:

Bash

Alias