1

If I run this:

#!/usr/bin/env bash

simple_return_zero(){
  return 0;
}

simple_return_one(){
  return 1;
}

if [ simple_return_zero ]; then
   echo "we have 0000";
fi

if [ ! simple_return_zero ]; then
   echo "we have not 00000";
fi

if [ simple_return_one ]; then
   echo "we have 11111";
fi

if [ ! simple_return_one ]; then
   echo "we have not 11111";
fi

I get:

we have 0000
we have 11111

I know the above is the wrong code to use, I think this is the right way to do it:

if simple_return_zero; then
   echo "we have 0000";
fi

if ! simple_return_zero; then
   echo "we have not 00000";
fi

if simple_return_one; then
   echo "we have 11111";
fi

if ! simple_return_one; then
   echo "we have not 11111";
fi

and now we get something more expected:

we have 0000
we have not 11111

My question is - why doesn't the test command ( [ ] ) work in this case? Doesn't the test command check for exit codes / return codes???

  • also, if there is a better way to run/organize the code, pls lmk...it's a little awkward with the ! in front of the command without any [ ] braces. – Alexander Mills Jun 14 '18 at 0:42
2

Doesn't the test command check for exit codes / return codes???

Absolutely not. It performs the test as defined by the text within the brackets, whose syntax can be viewed via help test.

if on its own checks the return code of the command executed.

  • humma but what does test actually do if there is no comparison operator? for example if it's just a command in between the brackets? – Alexander Mills Jun 14 '18 at 0:51
  • From help test: "STRING True if string is not empty." – Ignacio Vazquez-Abrams Jun 14 '18 at 0:51
  • Ah yes that makes sense, fml – Alexander Mills Jun 14 '18 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.