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