I would like to test a Bash function's return value in an if statement like this:
if [[ func arg ]] ; then …
But I get error messages like: conditional binary operator expected.
What is the right way to do this?
Is it the following?
if [[ $(func arg) ]] ; then ...
Return Values When a bash function completes, its return value is the status of the last statement executed in the function, 0 for success and non-zero decimal number in the 1 - 255 range for failure. The return status can be specified by using the return keyword, and it is assigned to the variable $? .
Checking Bash Exit Code Launch a terminal, and run any command. Check the value of the shell variable “$?” for the exit code. $ echo $? As the “date” command ran successfully, the exit code is 0.
To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"
If it was the exit code and not the result, you could just use
if func arg; then ...
If you cannot make the function return a proper exit code (with return N
), and you have to use string results, use Alex Gitelman's answer.
$ help if
:
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Execute commands based on conditional.
The
if COMMANDS
list is executed. If its exit status is zero, then thethen COMMANDS
list is executed. Otherwise, eachelif COMMANDS
list is executed in turn, and if its exit status is zero, the correspondingthen COMMANDS
list is executed and the if command completes. Otherwise, theelse COMMANDS
list is executed, if present. The exit status of the entire construct is the exit status of the last command executed, or zero if no condition tested true.
Exit Status: Returns the status of the last command executed.
If you need to test two conditions, one being the exit status of function/command and the other e.g. value of variable, use this:
if func arg && [[ $foo -eq 1 ]]; then echo TRUE; else echo FALSE; fi
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