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
?
Here's how I'm doing it, though I'm not sure it's the best way:
The major downsides here are that I rely on
sed
, and my means of dropping any arguments in the alias stops at the first space, expecting that no alias shall ever point to a program which, for some reason, has spaces in its name (i.e.alias badprogram='A\ Very\ Bad\ Program --some-argument'
), which is a reasonable enough assumption, but still. I think that at least the wholesed
part could be replaced by maybe something leveraging bash's own parsing/splitting/tokenization of command lines, but I wouldn't know where to begin.Here's a version I wrote that does not rely on any external commands and also handles recursive aliases without creating an infinite loop: