Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement and calling function in if using bash

I have written a function:

check_log(){     if [ -f "/usr/apps/appcheck.log" ]     then          return 1     else          return 0     fi } 

Then I call this function in an "if" condition:

if [ check_log ]; then     ........statements.... fi 

Will this work? I am confused here because bash returns 0 on success and 1 on failure, but my function is returning 1 and the condition is checking for 1/0, it gets 1 and it should give failures, but in my shell script the condition is passing.

Can anyone shed light on this issue?

like image 585
JumpOffBox Avatar asked Mar 27 '13 19:03

JumpOffBox


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.

How do you write and call a function in bash?

Creating a Function in Bash The code between the curly braces {} is the function body and scope. When calling a function, we just use the function name from anywhere in the bash script. The function must be defined before it can be used.

What is bash if [- N?

A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.


1 Answers

if [ check_log ]; 

When you use square brackets you're invoking the test command. It's equivalent to if test check_log which is shorthand for if test -n check_log, which in turn means "if "check_log" is not an empty string". It doesn't call your check_log function at all.

Change it to this:

if check_log; 

By the way, the function could be more simply written as:

check_log() {     ! [ -f "/usr/apps/appcheck.log" ] } 

The return value from a function is the exit status of the last command, so no need for explicit return statements.

like image 109
John Kugelman Avatar answered Sep 22 '22 12:09

John Kugelman