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 [].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With