bash versus sh test builtin

George Davidovich freebsd at optimis.net
Sun Jan 11 19:53:03 PST 2009


On Sun, Jan 11, 2009 at 08:08:18PM -0600, Jeffrey Goldberg wrote:
> The -ne operator for [ in /bin/sh doesn't seem to work as in bash.   
> Also the bash behavior here is what matches /bin/[ most closely.
> 
> $ /bin/sh
> $ if [ $UID -ne 0 ] ; then
>  > echo not root
>  > fi
> [: -ne: unexpected operator
> $ exit
> $ echo $SHELL
> /usr/local/bin/bash
> [jeffrey at dobby ~/src/mount-rsnap]$ if [ $UID -ne 0 ] ; then
>  > echo not root
>  > fi
> not root
> 
> Does anyone have a recommendation of how to run this simple test in / 
> bin/sh 

if [ $(id -u) -ne 0 ]; then ...

As to why your test isn't working as expected, rewrite your script to
read:

#!/bin/sh
echo $UID

and you'll discover that UID is a bash environmental variable.

> and how to write tests reasonably portably?

That's a different question, and merits a much longer discussion
probably better had elsewhere.  I'd suggest comp.unix.shell.

-- 
George


More information about the freebsd-questions mailing list