Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In bash, can you use a function call as a condition in an if statement?

Tags:

bash

here's what i'm trying to achive:

function f1() {   return 0 }  function f2() {   return 0 }  if [[ f1 && f2 ]]; then   echo "success" else   echo "fail" fi 
like image 449
chickeninabiscuit Avatar asked Nov 14 '11 05:11

chickeninabiscuit


People also ask

Can you put a function call in an if statement?

It depends. If words is a Set that already contains an equal object, it won't add it. Please read the doc before asking this kind of question. By the way when you call a function whether it's in a statement (if, try ...) the function is still called and the body executed so yes the obj will be addded to words.

Can we call a function inside a function in shell script?

In the myScript.sh file, we've defined a variable VAR and two functions: log_info() and log_error(). We can call the functions within the script file.

Can a Bash function call itself?

Functions in Bash also support recursion (the function can call itself). For example, F() { echo $1; F hello; sleep 1; } . A recursive function is a function that calls itself: recursive functions must have an exit condition, or they will spawn until the system exhausts a resource and crashes.


1 Answers

You don't use [[ (or [) when running a command and checking the result code.

if f1 && f2 ; then   echo "success" else   echo "fail" fi 
like image 69
Ignacio Vazquez-Abrams Avatar answered Sep 25 '22 17:09

Ignacio Vazquez-Abrams