Skip to main content

Get the expansion of an alias (in both bash and zsh) [Resolved]

I want to get the text which an alias expands into.

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.


Question Credit: Tom Hale
Question Reference
Asked August 22, 2018
Tags: bash, shell, alias
Posted Under: Unix Linux
9 views
4 Answers

Thanks to Stéphane Chazelas' answer, I came up with:

# Expand an alias as text - https://unix.stackexchange.com/q/463327/143394
function expand_alias {
  if [[ $ZSH_VERSION ]]; then
    # shellcheck disable=2154  # aliases referenced but not assigned
    printf '%s\n' "${aliases[$1]}"
  else  # bash
    printf '%s\n' "${BASH_ALIASES[$1]}"
  fi
}

credit: Tom Hale
Answered August 22, 2018
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA