[buug] ~, shell script programming, etc. (wee bits from last BUUG meeting, plus a bit more
Michael Paoli
Michael.Paoli at cal.berkeley.edu
Mon May 11 20:52:16 PDT 2009
from an sh(1) man page:
Tilde Expansion (substituting a user's home directory)
A word beginning with an unquoted tilde character (~) is subjected to
tilde expansion. All the characters up to a slash (/) or the end of the
word are treated as a username and are replaced with the user's home
directory. If the username is missing (as in ~/foobar), the tilde is
replaced with the value of the HOME variable (the current user's home
directory).
$ echo ~
/home/m/michael
$ echo \~
~
$ echo '~'
~
$ echo "~"
~
$
But not all shells are created equal - notice the differing behaviors
between bash and dash, for the versions at my fingertips, in the case
where HOME isn't set:
$ bash -c 'unset HOME; echo ~'
/home/m/michael
$ dash -c 'unset HOME; echo ~'
~
$
Somewhat hazardous:
#!/bin/sh
cd ~/some_directory
./some_program
A bit better:
#!/bin/sh
cd ~/some_directory &&
./some_program
Typically even better for a shell script:
#!/bin/sh
set -e
cd ~/some_directory
./some_program
With -e set, upon error (non-zero return for shell command) the shell
exits non-zero, rather continuing execution. This is typically what one
wants.
references:
2009-05-07 BUUG meeting
sh(1)
http://www.rawbw.com/~mp/unix/sh/#Good_Programming_Practices
More information about the buug
mailing list