Bash – Get the Expansion of an Alias in Bash and Zsh

aliasbashshellzsh

I want to get the expansion of an alias.

For example, if I have:

alias g=hub
alias cdh='cd $HOME'

I want to have:

expand_alias g == hub

expand_alias cdh == cd $HOME

The tricky thing is that the two shells have different output:
bash:

$ alias g cdh
alias g='git'
alias cdh='cd $HOME'

zsh:

% alias g cdh
g=hub
cdh='cd $HOME'

Note no alias prefix and no quotes around hub.

Best Answer

In zsh, you can just use

get_alias() {
  printf '%s\n' $aliases[$1]
}

With bash (assuming it's not in POSIX mode in which case its alias would give an output similar to zsh's), you could do:

get_alias() (
  eval '
    alias() { printf "%s\n" "${1#*=}"; }'"
    $(alias -- "$1")"
)

Basically, we evaluate the output of alias after having redefined alias as a function that prints what's on the right of the first = in its first argument.

You could use a similar approach for something compatible with most POSIX shells, zsh and bash:

get_alias() {
  eval "set -- $(alias -- "$1")"
  eval 'printf "%s\n" "${'"$#"'#*=}"'
}
Related Question