3

Suppose I have a function foo which takes two parameters and returns true or false, I would like to use it within the test [ command in bash, some thing like this

param1=one
param2=two
if [ foo $param1 $param2 ]; then
    do something
fi

I know this works with out using [] like this,

if foo $param1 $param2; then .....

But I want to use it with in [].

4
  • What do you want, the output code of the command or what it returns? Commented Oct 7, 2014 at 15:49
  • 2
    If it works without the brackets (using the exit status), then there is no need to run in with the test command. Commented Oct 7, 2014 at 16:04
  • Why do you want to use it inside test? Are you trying to test whether it emits output, rather than its exit status? Commented Oct 7, 2014 at 17:52
  • I am trying to understand how test works. Commented Oct 8, 2014 at 6:14

2 Answers 2

4

If you want to test whether the exit status of your command indicates success or failure, leave off the brackets entirely; using the test command in that use case is wrong, full-stop.

In this case,

if foo "$param1" "$param2"; then ...; fi

is the only correct syntax that isn't needlessly inefficient.


It's certainly possible to emit $? inside your subprocess, and check the output of that using test, like so:

if [ "$(foo "$param1" "$param2" >&2; echo "$?")" -eq 2 ]; then ...; fi

...but see again re: "needlessly inefficient"; this would be better written as:

foo "$param1" "$param2"; retval=$?
if [ $retval -eq 2 ]; then ...; fi

...avoiding all the overhead of an unnecessary subshell.


If you want to test whether the output of your command is non-empty (typically an undesirable / unnecessary operation, as most standard UNIX commands can indicate whether they operated correctly, whether they found what they were searching for, etc. via exit status):

if [ -n "$(foo "$param1" "$param2")" ]; then ...; fi

is correct.


One important thing to keep in mind -- any use of $() moves your function from running inside of the parent shell (and thus able to update or modify that shell's state) into a subshell. So -- if your function is supposed to change variables or state inside the shell, using $() will modify its behavior.

Sign up to request clarification or add additional context in comments.

Comments

2

test or [ ] evaluates expressions, not the exit status of a function.

To evaluate the exit status of a function / command, use if in the way you're using it:

if foo "$param1" "$param2"; then .....

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.