home | list info | list archive | date index | thread index

Re: expansion of tilde for home directory

> DIR="/home/$(basename ~)/Something/"

As others have pointed out, it's the unquoted tilde in the command
substitution that is expanding above.  You could have used this (but
don't):

    DIR="$(echo ~)/Something/"

As others have said, quoting (even double quoting) hides tilde expansion.
Just make sure the tilde isn't inside quotes and it works fine:

    DIR=~/"Something"

> Heck, I'd just if [ -d ~/Something ]; then

No, not if "Something" is text or a variable that could include spaces
or GLOB characters.  Always double-quote your variables.

Since the tilde is exactly equivalent to $HOME, this is cleanest:

    DIR="$HOME/Something"
    if [ -d "$DIR" ] ; then ...

> I would also assume that if this command was run as root it would not
> work, as root's home directory is /root. Same for any other user whose
> home directory is not under /home. Perhaps a few-lines script would
> first have to grep the login ID from /etc/passwd (read-only, so OK),
> parse the line to get the actual home directory and return it.

None of the above is needed if you only want the HOME directory of the
person running the script.  All that work is already done for you and
sitting in your $HOME environment variable.  The one line:

    DIR="$HOME/Something"

Works for any user, even root, even on old shells that don't expand
tildes, even if $HOME or Something contains blanks or GLOB characters.

*ALWAYS DOUBLE QUOTE YOUR VARIABLE EXPANSIONS*

https://teaching.idallen.org/cst8207/19w/notes/320_shell_variables.html#double-quote-all-uses-of-variables

-- 
| Ian! D. Allen, BA, MMath  -  idallen [ at ] idallen [ dot ] ca - Ottawa, Ontario, Canada
| Home: www.idallen.com   Contact Improvisation Dance: www.contactimprov.ca
| Former college professor (Free/Libre GNU+Linux) at:  teaching.idallen.com
| Defend digital freedom:  http://eff.org/  and have fun:  http://fools.ca/

To unsubscribe send a blank message to linux+unsubscribe [ at ] linux-ottawa [ dot ] org
To get help send a blank message to linux+help [ at ] linux-ottawa [ dot ] org
To visit the archives: https://lists.linux-ottawa.org