3

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???

1
  • 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. Commented Jun 14, 2018 at 0:42

1 Answer 1

5

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.

3
  • 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? Commented Jun 14, 2018 at 0:51
  • From help test: "STRING True if string is not empty." Commented Jun 14, 2018 at 0:51
  • Ah yes that makes sense, fml Commented Jun 14, 2018 at 0:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .