[CLUE-Tech] shell programming
marcus hall
marcus at tuells.org
Wed Dec 11 07:30:30 MST 2002
On Wed, Dec 11, 2002 at 03:26:36AM -0700, Dave Price wrote:
> When you 'su' your $USER variable does not change, but your $UID
> variable does. (root's UID is 0 {zero})
...
>
> if [ $USER = root ]
...
> if [ $UID = 0 ]
Of course, if this script does anything where it *really* matters what
the user is, don't rely on a variable from the environment, as it is
trivial to set it before invoking the script. You could use $(id -un)
to compare against root, or $(id -u) to compare against 0.
Also, especially if you have not set the variable in your script, it is
generally unsafe to write a comparison that way. It's too easy to get
a syntax error if the variable contains unexpected text. For instance,
if USER was null, the test becomes:
if [ = root ]
which gives an error "[: =: unary operator expected". It is better to
enclose the $USER in double quotes:
if [ "$USER" = root ]
However, this could still be confused if $USER contained an unexpected
value like "-a", since then the test becomes:
if [ -a = root ]
It seems that recent implementations parse this much better, as trying
this out I correctly get a false return from the test, but in previous
shells you would get an error message about a missing argument before
the -a. That is why you will frequently see tests written like:
if [ "X$USER" = Xroot ]
The leading X added to the 1st argument prevents it from inadvertently
appearing as a special argument that test recognizes.
marcus hall
marcus at tuells.org
More information about the clue-tech
mailing list