September 04, 2013

A bashism a week: tilde expansion

Did you know that you can get a user's home directory with the "~username" tilde expansion? You probably do, but how about other tilde expansions?

Thanks to a few bashisms you can make your script even more difficult to read by using "~+" to get $PWD, and "~-" to get $OLDPWD.

Are you using bash and want to access the directories stack created when using the pushd and popd bashisms? The ~i (where i is an integer) expansion can give you that. It gives you forward (~+i) and backward (~-i) access to the directories stack.

But beware, if the directories stack is smaller than the number you used, there won't be any expansion.

When using tildes in shell scripts, make sure you quote to avoid unwanted expansions. Note that the posh shell in wheezy and older do support those non-POSIX expansions.

in the first examples the tilde is quoted for easier reading; the expansion doesn't occur if the tilde is quoted.

1 comment:

  1. GNU bash is actually not the shell with the most tilde expansions: it appears to cowardly refuse to expand ~ after = (like export foo=~bar or dd of=~/x), which mksh does perfectly well.

    pushd/popd/dirs originally come from the Berkeley C Shell (considered harmful), which doesn’t have the tilde expansion, so tilde+number is a true bashism (not in mksh either).