Articles
Software
Gallery
Other works
Contacts

Tilde_home_is_the_worst_Bash_feature


Bash defines the sequence "~[user]" to expand to the home directory of [user], where the current one is the default user.

For example:

    ~       -> your home directory
    ~root/  -> roots home directory

This would be all well, if not for the expansion being only done on unquoted strings, with no other way provided out-of-the-box to perform the transformation.

That's why one can see hacks such as span (class: code) { do_stuff "$(echo $mypath)" } quite often in the wild.

Try this for yourself:

    echo First  example: ~/Desktop
    echo Second example: ~/Desktop/Cat_picture_collection_(1994-1996)/

Oh, my bad! The last one has a syntax error because "()"s have special significance in Bash. Let's just quote it...

    echo Second example - fixed: "~/Desktop/Cat_picture_collection_(1994-1996)/"

No, wait, again, the tilde will fail to expand, because its quoted. We must not quote that part.

    echo Second example - fixed - fixed: ~/"Desktop/Cat_picture_collection_(1994-1996)/"

This is ok. Well, as long as we don't wish to work on variables. In which case, we are fucked, since neither echo $MYVAR nor echo "$MYVAR" will give us the desired result, let alone something non-hacky.

One common approach is to just replace '~' with ${HOME}. Which is the best, one is reasonable to do, without potentially doubling his script by properly evaluating '~', but that may lead to some unfortunate situations where:

    ~root/  ->  /hone/anon/root/

And, all this could have been prevented by adding a "realhome" builtin.