在bash中使用退出代码
我有一个bash脚本,它对我的??源代码运行三次检查,然后如果所有命令都成功则退出0,如果其中任何一个失败则退出1:
#!/bin/bash test1 ./src/ --test-1=option exit_1=$? test2 ./src/ test-2-options exit_2=$? test3 ./src/ -t 3 -o options exit_3=$? # Exit with error if any of the above failed [[ $exit_1 -eq 0 && $exit_2 -eq 0 && $exit_3 -eq 0 ]] exit $? 这段代码有效,但感觉过长且冗长.有什么方法可以做得更好吗?具体来说,我不满意: >必须运行命令,然后将退出代码分配给变量 理想情况下,最终结果将更具可读性: exit_1=( test1 ./src/ --test-1=option ) exit_2=( test2 ./src/ test-2-options ) exit_3=( test3 ./src/ -t 3 -o options ) # Exit with error if any of the above failed exit ( $exit_1 && $exit_2 && $exit_3 ) 我考虑过的一些事情: 将错误代码放入一行中的变量: exit_1=$( test1 ./src/ --test-1=option )$? exit_2=$( test2 ./src/ test-2-options )$? exit_3=$( test3 ./src/ -t 3 -o options )$? 这有效,并使这一点缩短,但我以前从未见过其他任何人使用它.这是一个明智/理智的事情吗?这有什么问题吗? 只是运行测试,和&&他们在一起: test1 ./src/ --test-1=option && test2 ./src/ test-2-options && test3 ./src/ -t 3 -o options status=$? 这不起作用,因为bash短路.如果test1失败,test2和test3不会运行,我希望它们全部运行. 使用||检测错误并退出出口 [[ $exit_1 -eq 0 && $exit_2 -eq 0 && $exit_3 -eq 0 ]] || exit 1 这样可以节省一行尴尬的退出代码和变量,但是退出1的重要位置现在位于可以错过它的行的末尾.理想情况下,这样的事情会起作用: exit [[ $exit_1 -eq 0 && $exit_2 -eq 0 && $exit_3 -eq 0 ]] 当然,这不起作用,因为[[返回其输出而不是回显它. exit $( [[ $exit_1 -eq 0 && $exit_2 -eq 0 && $exit_3 -eq 0 ]] ; echo $? ) 确实有效,但看起来仍然像一个可怕的污泥 没有明确处理exit-codes-as-boolean [[ $exit_1 && $exit_2 && $exit_3 ]] 这不符合你希望它会做的事情.最简单的&& amp;存储在变量中的三个返回码与$var -eq 0&& ….当然有一个更好的方式? 我知道bash不是一个很好的编程语言 – 如果你甚至可以称之为 – 但是有什么办法可以让它变得不那么尴尬吗?
您可以使用bash的算术命令将退出代码组合在一起,并取消结果,如果任何代码非零,则退出代码为1.首先,一个例子:
$! (( 0 | 0 | 0 )); echo $? 0 $! (( 1 | 0 | 0 )); echo $? 1 现在,你的脚本: #!/bin/bash test1 ./src/ --test-1=option; exit_1=$? test2 ./src/ test-2-options; exit_2=$? test3 ./src/ -t 3 -o options; exit_3=$? # Exit with error if any of the above failed. No need for a final # call to exit,if this is the last command in the script ! (( $exit_1 || $exit_2 || $exit_3 )) 或者通常,您可以在运行任意数量的测试时累积退出代码: #!/bin/bash # Unfortunately,||= is not an assignment operator in bash. # You could use |=,I suppose; you may not be able to assign # any meaning to any particular non-zero value,though. test1 ./src/ --test-1=option; (( exit_status = exit_status || $? )) test2 ./src/ test-2-options; (( exit_status = exit_status || $? )) test3 ./src/ -t 3 -o options; (( exit_status = exit_status || $? )) # ... testn ./src "${final_option_list[@]}"; (( exit_status = exit_status || $? )) exit $exit_status # 0 if they all succeeded,1 if any failed (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |