Using $? in an if statement

Add a space after the [, and another before ]:

function foo {
   (cd "$FOOBAR";
   <some command>
   if [ "$?" -ne 0 ]
   then
      echo "Nope!"
   else
      echo "OK!"
   fi
   )
}

[ is a shell builtin, it is a command just like echo, read, expr... it needs a space after it, and requires a matching ].

Writing [ "$?" -ne 0 ] is actually invoking [ and giving it 4 parameters: $?, -ne, 0, and ].

Note: the fact that you are getting an error saying [1: command not found means that $? was having the value of 1.


Or you could skip $? altogether. If your command is cmd, the following should work:

function foo {
   (cd $FOOBAR;
   if cmd
   then
      echo "OK!"
   else
      echo "Nope!"
   fi
   )
}

It's good practice to assign the return value to a variable before using it

retval="$?"
if [ $retval -ne 0 ]

It allows you to reuse the return value. e.g. in an if... elif... else... statement.

Tags:

Scripting

Bash