如果使用bash的if语句和调用函数 [英] if statement and calling function in if using bash
问题描述
我写了一个函数:
check_log(){
if [ -f "/usr/apps/appcheck.log" ]
then
return 1
else
return 0
fi
}
然后我在"if"条件下调用此函数:
Then I call this function in an "if" condition:
if [ check_log ];
then
........statements....
fi
这项工作有效吗?我在这里感到困惑,因为bash成功返回0,失败返回1,但是我的函数返回1
并且条件正在检查1
/0
,它得到1
并且应该给出失败,但是在我的shell脚本条件通过了.
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?
推荐答案
if [ check_log ];
使用方括号时,将调用test
命令.它等效于if test check_log
,它是if test -n check_log
的简写,反过来意味着如果"check_log"
不是空字符串".它根本不会调用您的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.
将其更改为此:
if check_log;
顺便说一句,该函数可以更简单地写为:
By the way, the function could be more simply written as:
check_log() {
! [ -f "/usr/apps/appcheck.log" ]
}
函数的返回值是最后一条命令的退出状态,因此不需要显式的return语句.
The return value from a function is the exit status of the last command, so no need for explicit return statements.
这篇关于如果使用bash的if语句和调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!