bashalias

How do I get an alias value?


In my alias file, I already have defined:

alias e='eza --long --recurse --dereference …'

I want to add a variant of that, which adds another option at the end:

alias et='eza --long --recurse --dereference … --tree'

Instead of repeating the code, I would like to reuse the value of e, I tried:

alias et="$(alias e) --tree"

This gives the wrong result because the command alias KEY outputs in the format alias KEY=VALUE where VALUE is appropriately quoted. The documentation calls that reusable format.

I need the value of the alias, unquoted.

alias et="$(alias-value-unquoted e) --tree"
# hypothetical ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

How do I do that?


Solution

  • In the simple case you can repeat the alias. Per the manual: The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. So this works:

    user@host: alias f='echo foo'
    user@host: f
    foo
    user@host: alias g='f bar'
    user@host: g
    foo bar
    

    In more complex cases you should switch to functions. For example:

    e() {
      eza --long --recurse --dereference "$@"
    }
    
    et() {
      e "$@" --tree
    }
    

    Note that functions are almost always preferred over aliases, as functions are generally easier to write (no extra quoting or escaping of special characters required) and are more flexible with support for arguments. The last line of the Aliases entry in the manual even states: For almost every purpose, shell functions are preferred over aliases.