Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to test a Bash function's return value?

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 ... 
like image 446
grok12 Avatar asked Jun 05 '11 05:06

grok12


People also ask

How do I return a value from a bash script?

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

How do I check my bash return?

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.

How do you check if a variable has a value in bash?

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"


2 Answers

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 the then COMMANDS list is executed. Otherwise, each elif COMMANDS list is executed in turn, and if its exit status is zero, the corresponding then COMMANDS list is executed and the if command completes. Otherwise, the else 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.

like image 179
kay Avatar answered Oct 13 '22 05:10

kay


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 
like image 42
Pedro Inácio Avatar answered Oct 13 '22 06:10

Pedro Inácio