if statement and calling function in if using bash
As noted by @john-kugelman, one solution (and perhaps the most correct one) is to use the following syntax:
if check_log;
But an alternative solution is:
if [[ $(check_log; echo $?) -eq 0 ]];
My personal preference is the latter as it fosters consistency among conditional statements. But the downside is that because it relies on command substitution, it will fork a child process (i.e. a subshell) where as the first method will not.
An interesting read on the subject can be found here:
When does command substitution spawn more subshells than the same commands in isolation?
Updated (2020-12-01): In most cases it is inadvisable to use the above alternative solution for reasons related to inefficiency and the potential to trigger erroneous results especially if the called function writes to stderr or stdout and that output isn't trapped.
Updated (2017-10-20): Strikeout my preference for the second method as these days I'm on a mission to prevent unnecessary forking. The syntax in the first solution is not as intuitive for non-shell programming, but it certainly is more efficient.
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.