Reputation: 1089
I am new in shell script, trying to catch the return value of a program, and do something with it.
I have this script below
#!/bin/sh
if [ $# !=2 ] ; then
echo "Usage : param1 param2 "
exit 1;
elif [ $# -eq 2 ]; then
./callprogram
$out = $?
echo "$out"
fi
if [ $out==0 ]; then
echo "out ok"
fi
It keeps getting me error of
"[: 11: 0: unexpected operator
out ok
I have no clue why line 11 is wrong. if I remove "fi", it will promt that it needs "fi". Can anyone help with this matter?
Thank you
Upvotes: 1
Views: 4206
Reputation: 31182
Change:
if [ $out==0 ]; then
to:
if [ $out = 0 ]; then
add spaces, and change '==' to '='. Note, that bash, executed as a bash accepts ==
. But if you run is as a sh it will say "unexpected operator".
Why:
The [
is a command (or symlink to test binary, depending on your OS and shell). It expects $out
and ==
and 0
and ]
to be separate command arguments. If you miss the space around them, you have one argument $out==0
.
BTW:
It's safer to always enquote the variables like that:
if [ "$var" ......
instead of
if [ $var
because when variable is empty, then you can get another error because of wrong number of arguments (no argument instead of empty string).
Upvotes: 2
Reputation: 212464
You have several problems. The one that is giving you the error is that you need a space after != on
if [ $# != 2 ]
(although -ne
would be better than !=
). It appears that you are calling the script with 11 arguments, and then calling [ with the arguments 11 !=2
, and it does not know what to do with !=2 because you meant != 2
but forgot the space. Also, you want
out=$?
on the assignment (no $ on the LHS) and
if [ $out = 0 ]
on the comparison. (Spaces around the operator, which is '=' instead of '=='. '==' will work on many shells, but '=' works in more shells.)
But your script would be better written without the explicit reference to $?
#!/bin/sh if test $# != 2; then echo "Usage: $0 param1 param2 " >&2 # Errors go to stderr, not stdout exit 1; fi # you know $# is 2 here. No need to check if ./callprogram; then echo "out ok" fi
Upvotes: 1
Reputation: 274758
You need a space after the [
and you need to use -eq
(equals) or -ne
(not equals) to compare numbers in your if-statement.
To assign a variable use out=$?
, not $out = $?
. There should be no spaces on either side of the =
sign.
Try this:
if [ $# -ne 2 ] ; then
echo "Usage : param1 param2 "
exit 1
elif [ $# -eq 2 ]; then
./callprogram
out=$?
echo "$out"
fi
if [ $out -eq 0 ]; then
echo "out ok"
fi
Upvotes: 3