Sunday, May 19, 2013

Bash aliases and variables don't mix

For a long time, I've used bash aliases such as:
alias hgrep='history | grep $1'
and they've worked just fine. However, when I've tried to do something a bit more complicated, such as:
alias hprju='heroku $1 --app project $2'
it fails with an error message:
!    `--app` is not a heroku command.
Bummer! What I finally realized is that the first example isn't actually replacing $1 with what I specified on the command line. Instead, $1 has NO replacement and my additional text is simply appended to the end of the line. To see how this works, just run the following:
alias test='ls'
test /etc
and you'll get a directory listing of /etc. After some googling -- with a number of questions along the lines of "Why doesn't my first example work and not my second?" -- I found this link, where the 2nd answer had the key. The Bash Reference Manual section on Aliases clearly states:
There is no mechanism [my emphasis] for using arguments in the replacement text, as in csh. If arguments are needed, a shell function should be used (see Shell Functions).
This situation has bugged me off and on for some time and I'm glad to finally understand what's happening. Hope it helps someone else.

No comments:

Post a Comment