Bash – Using $? in an if statement

bashscripting

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

I am trying to write a function like the one above and place it in my .bashrc file. After I source the file and run, I get:

Total time: 51 seconds
-bash: [1: command not found
OK!

Can someone help me understand what I did wrong?

Best Answer

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.

Related Question