为什么我的函数调用在下面的 if 条件中没有计算为布尔值?
从函数调用返回时是否必须对布尔值使用数字?
#!/bin/bash
#Script to wait for log file to start and open it using less
function is_log_started()
{
if test -f "log/server.log"; then
return true
fi
return false
}
if [ is_log_started = true ]; then
echo "log started"
fi
Run Code Online (Sandbox Code Playgroud)
您只能从 shell 函数返回 0 到 255 之间的整数。这与适用于可执行文件的限制相同。如果你传递一个非数字参数,不同的 shell 会有不同的反应;bash 确实会打印出错误消息。
$ bash -c 'f () { return true; }; f; echo $?'
bash: line 0: return: true: numeric argument required
2
Run Code Online (Sandbox Code Playgroud)
为真传递 0,为假传递 1 到 125 之间的任何值,与退出程序时相同。从 126 到 255 的值也是假的,但它们具有常规含义(无法启动程序,或程序被信号杀死)。
function is_log_started()
{
if test -f "log/server.log"; then
return 0
fi
return 1
}
Run Code Online (Sandbox Code Playgroud)
但这是一种复杂的写作方式
function is_log_started
{
test -f "log/server.log"
}
Run Code Online (Sandbox Code Playgroud)
shell 函数的返回状态是执行的最后一条语句的返回状态。
你的测试也是错误的。[ is_log_started = true ]
测试is_log_started
和是否true
是同一个字符串。要测试函数调用的返回状态是否为真,您只需调用该函数。每个 shell 命令已经是一个布尔值:如果命令返回 0,则为 true,否则为 false。
function is_log_started
{
test -f "log/server.log"
}
if is_log_started; then
echo "log started"
fi
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17216 次 |
最近记录: |