schemacs
schemacs

Reputation: 2891

why is wrong with 'if [ $# > 0 ] ; then'?

why does it still produce output in the third command?

$cat sh.sh
#!/bin/sh
echo $#
if [ $# > 0 ] ; then
    base=`basename $1 .c`
    echo $base
fi
$ sh sh.sh a.c
1
a
$ sh sh.sh
0
.c

I use this file:/usr/share/doc/opencv-doc/examples/c/build_all.sh to build the c examples for opencv packages,but failed with similar errors.

Upvotes: 3

Views: 14127

Answers (3)

pepoluan
pepoluan

Reputation: 6808

Remember that [ is a command. /usr/bin/[ , to be exact. It is linked to the command /usr/bin/test

So, [ $# > 0 is identical to test $# > 0, i.e., redirect test $#'s output to the 0 file.

If you're using bash ... now that's a different story altogether :-)

Upvotes: 2

codaddict
codaddict

Reputation: 455272

You need to use -gt in place of >.

You can use > if you are using double parenthesis construct.

Upvotes: 7

dogbane
dogbane

Reputation: 274738

You should use -gt(Greater than) in your condition, not >. Look at man test for more information.

if [ $# -gt 0 ] ; then
    base=`basename $1 .c`
    echo $base
fi

Upvotes: 2

Related Questions