With a little side of applesauce...

Friday, November 23, 2007

bash - variables in aliases




When trying to setup an alias to tar up folders with long names, I
simply wanted something like this:

tar -cf this-is-a-really-long-foldername.tar
this-is-a-really-long-foldername


I figured that an alias would be the easiest thing to do:

alias taritup="tar -cf ${1}.tar ${1}"


If you add this to your .bashrc and source it, then test it, it
appears to be working, but the tarball never appears... Strange.

The Bash Reference manual says that variables aren't expanded in
aliases:

There is no mechanism for using arguments in the replacement text, as
in csh. If arguments are needed, a shell function should be used (see
section 3.3 Shell Functions).

http://www.gnu.org/software/bash/manual/bashref.html#SEC79

But, interestingly enough, I can get positional parameters to
expand... once :P Let's change our example alias above:

alias taritup="tar -cf ${1}.tar ${2}"


Hmmm... Ok, the same thing happens. It appears to be doing
something, but the tarball is not created. Next, try this:

alias taritup="tar -cf x.tar ${1}"


That works... But then:

alias taritup="tar -cf x.tar ${2}"


Fails with the following:

me@mylaptop:~/tmp$ taritup x emacs_autosaves/
tar: x: Cannot stat: No such file or directory
tar: Error exit delayed from previous errors


I haven't followed this through, but obviously we are able to use a
single argument in an alias. My final fix was to use a function, (as
recommended):

function xtest() { tar -c --exclude CVS -f ${1}.tar ${1}; }


No comments: