On my system*
cd # move to home
mkdir tempdir
PATH="$PATH:~/tempdir" # put tempdir in path
touch tempdir/tempscript
echo -e '#!/bin/bash\necho h' > tempdir/tempscript # write script
chmod u+x tempdir/tempscript # make executable
tempscript # execute
will find the script tempdir/tempscript
and print h
.
However, if we echo $PATH
, we will see ~/tempdir
at the end of it, so it was not expanded. Which is what we expect to happen, since we put double quotes around the assignment.
I can't find any documentation however on why tilde expansion occurs when evaluating $PATH
. (Note that the PATH variable still has the ~
in it.)
Is this portable behavior?
* Mac OS X w/ GNU bash 3.2
No, this is not portable. If your operating system's execl
call doesn't perform this expansion, programs that aren't bash will fail to find executables within the given directory.
Note that if you didn't quote the expansion, this would be safe:
PATH=$PATH:~/tempdir # this is safe -- expansion happens before assignment
PATH="$PATH:~/tempdir" # this is not -- readers are required to expand
While it's generally a best practice to quote all shell expansions, this isn't necessary for assignments, which implicitly prevent string-splitting and glob expansion behaviors.