如何使用函数返回作为 if else then 快捷方式的条件?

dim*_*ech 6 bash shell-script

在某些情况下,函数需要执行并返回给调用者,这对我有用。

if tst; then
    echo "success"
else
    echo "failure"
fi

function tst () {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,我似乎无法使用快捷语法来做到这一点。我已经尝试了以下语句的多种组合,包括测试 if [[ tst = true ]] 或 if it = "0" 但我一直无法弄清楚。

[[ tst ]] && echo "success" || echo "failure"
Run Code Online (Sandbox Code Playgroud)

使用 bash 快捷语法在 if 条件下测试函数的正确方法是什么?

mur*_*uru 14

假设您要使用A && B || C,那么只需直接调用该函数:

tst && echo "success" || echo "failure"
Run Code Online (Sandbox Code Playgroud)

如果要使用[[,则必须使用退出值:

tst
if [[ $? -eq 0 ]]
then 
    ...
Run Code Online (Sandbox Code Playgroud)

  • @HaukeLaging 更新。但话又说回来,我会说如果一个人在做数字比较,应该使用`(())`来代替。 (2认同)

gle*_*man 5

(这不是真正的答案,更多的是评论)

你必须对a && b || c快捷方式有点小心:

  • 如果a返回成功,则b执行
  • 如果b随后返回退出状态,则c也将被执行。
$ [[ -f /etc/passwd ]] && { echo "file exists"; false; } || echo "file does not exist"
file exists
file does not exist
Run Code Online (Sandbox Code Playgroud)

if a; then b; else c; fi在这方面更安全,因为c不依赖于b,只a

$ if [[ -f /etc/passwd ]];then { echo "file exists"; false; }; else echo "file does not exist"; fi
file exists
$ echo $?
1
Run Code Online (Sandbox Code Playgroud)