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

Re: expansion of tilde for home directory

On Thu 2021-06-17 13:43:43 -0400, Ian! D. Allen wrote:
> 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"

Strictly speaking per spec this won't work. Tilde expansion happens
before parameter substitution. If it happens in any other order, that is
undefined behaviour and a portability issue.

So § 2.6 ¶ 2 of the 2018 rev of the spec.

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06

> > 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.

This is a literal. We all know what we are doing for space-less
literals. I would never imply otherwise for variables. It's in my
company policy, that I wrote, that there will be no exceptions even if
you know that the inputs are always safe, and it's there because humans
consistently make mistakes at least some times (or all the time for
juniors developers who learned shell script chaotically or haphazardly).

> 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.

I'm pretty sure that JFM meant that it doesn't look up the home of the
original user if you ran it under sudo (and expect nothing from su or
other). That'd be $SUDO_USER then, though it's only 40 more characters
to command sub then cut -d : -f …, like I said in a private email.

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