tgies tgies - 19 days ago 7
Bash Question

Programmatically dereference/resolve aliases in bash

I need to determine which command a shell alias resolves to in bash, programmatically; i.e., I need to write a bash function that will take a name potentially referring to an alias and return the "real" command it ultimately refers to, recursing through chains of aliases where applicable.

For example, given the following aliases:

alias dir='list -l'
alias list='ls'


where my function is
dereference_alias
,

dereference_alias list # returns "ls"
dereference_alias dir # also returns "ls"


Is there some builtin I don't know about that does this neatly, or shall I resign myself to scraping the output of
alias
?

Answer

Here's a version I wrote that does not rely on any external commands and also handles recursive aliases without creating an infinite loop:

# Arguments:
#
#   $1  Command to compact using aliases
#
function command-to-alias()
{
    local alias_key
    local guess

    local command="$1"
    local search_again="x"
    local shortest_guess="$command"

    while [[ "${search_again:-}" ]]; do
        unset search_again
        for alias_key in "${!BASH_ALIASES[@]}"; do
            guess="${command/#${BASH_ALIASES[$alias_key]}/$alias_key}"
            test "${#guess}" -lt "${#shortest_guess}" || continue
            shortest_guess="$guess"
            search_again="x"
        done
        command="$shortest_guess"
    done

    echo "$command"
}