PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 10, 2022

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

 December 10, 2022     bash, function, syntax     No comments   

Issue

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

Solution

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.



Answered By - kay
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing