Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Why does the following script display an "unexpected operator" message and fail when run with SH, but not with BASH.

!/bin/sh
if [ $UID -ne 0 ]
then
        echo "You must be root."
        exit 1
else
        echo "Open sesame."
        exit 0
fi
share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

Not all shells define a variable UID. This is a bash and zsh feature only. In other shells, the UID variable is not defined, so your test command expands to [ -ne 0 ] which is a syntax error.

A portable way to obtain the user ID is with the id utility.

if [ "$(id -u)" -ne 0 ]; then …
share|improve this answer
    
Thanks for the clarification! –  filmoreha Feb 5 '13 at 0:50
    
Another note is that quoting "$UID" would prevent the expansion from causing a syntax error. –  jordanm Feb 5 '13 at 3:57
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.