bash - 有没有一种优雅的方式来存储和评估 bash 脚本中的返回值?

标签 bash shell return-value sh

我在 bash 中有一系列相当复杂的命令,最终返回一个有意义的退出代码。脚本后面的各个地方都需要根据命令集是否成功进行条件分支。

目前我正在存储退出代码并对其进行数字测试,如下所示:

long_running_command | grep -q trigger_word
status=$?

if [ $status -eq 0 ]; then
    : stuff
else

: more code

if [ $status -eq 0 ]; then
    : stuff
else

出于某种原因,感觉这应该更简单。我们存储了一个简单的退出代码,现在我们重复输入数值测试操作以在其上运行。例如,我可以作弊使用字符串输出而不是更易于测试的返回代码:

status=$(long_running_command | grep trigger_word)

if [ $status ]; then
    : stuff
else

: more code

if [ $status ]; then
    : stuff
else

从表面上看,这看起来更直接,但我意识到它很脏。

如果其他逻辑不是那么复杂并且我只运行了一次,我意识到我可以将它嵌入到测试运算符的位置,但是当您需要在其他位置重用结果时这并不理想无需重新运行测试:

if long_running_command | grep -q trigger_word; then
    : stuff
else

到目前为止我唯一发现的是将代码分配为命令替换的一部分:

status=$(long_running_command | grep -q trigger_word; echo $?)

if [ $status -eq 0 ]; then
    : stuff
else

即使这在技术上不是一次性作业(尽管有些人可能认为可读性更好)但必要的数值测试语法对我来说仍然很麻烦。也许我只是强制症。

我是否缺少一种更优雅的方法来将退出代码分配给变量然后在其上分支?

最佳答案

简单的解决方案:

output=$(complex_command)
status=$?

if (( status == 0 )); then
    : stuff with "$output"
fi

: more code

if (( status == 0 )); then
    : stuff with "$output"
fi

或者更优雅一点

do_complex_command () { 
    # side effects: global variables
    # store the output in $g_output and the status in $g_status
    g_output=$(
        command -args | commands | grep -q trigger_word
    )
    g_status=$?
}
complex_command_succeeded () {
    test $g_status -eq 0
}
complex_command_output () {
    echo "$g_output"
}

do_complex_command

if complex_command_succeeded; then
    : stuff with "$(complex_command_output)"
fi

: more code

if complex_command_succeeded; then
    : stuff with "$(complex_command_output)"
fi

或者

do_complex_command () { 
    # side effects: global variables
    # store the output in $g_output and the status in $g_status
    g_output=$(
        command -args | commands
    )
    g_status=$?
}
complex_command_output () {
    echo "$g_output"
}
complex_command_contains_keyword () {
    complex_command_output | grep -q "$1"
}

if complex_command_contains_keyword "trigger_word"; then
    : stuff with "$(complex_command_output)"
fi

关于bash - 有没有一种优雅的方式来存储和评估 bash 脚本中的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21317997/

相关文章:

shell - AWK如何初始化具有多个要打印的字段的变量

c# - 关于 MathHelper.ToRadians(); 的问题

javascript - 如何根据 dblookup 结果在 xpages 中设置值字段?

linux - 安装和删除 DNSMasq 后本地服务器/Apache 无法工作 - macOS Sierra

linux - bash 和 s3cmd 无法正常工作

linux - 使用 grep 值创建文件

string - Bash:用字符串操作(百分号)

Linux命令行递归删除其他文件夹中不存在的文件

linux - 从键盘 bash 脚本控制变量

powershell - 如何获取在 Excel VBA 中运行的 Powershell 脚本的返回值?