Cal*_*leb 7 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
Run Code Online (Sandbox Code Playgroud)
出于某种原因,感觉这应该更简单.我们存储了一个简单的退出代码,现在我们重复输入数值测试操作来运行它.例如,我可以欺骗使用字符串输出而不是返回代码,这更容易测试:
status=$(long_running_command | grep trigger_word)
if [ $status ]; then
: stuff
else
: more code
if [ $status ]; then
: stuff
else
Run Code Online (Sandbox Code Playgroud)
从表面上看,这看起来更直接,但我发现它很脏.
如果其他逻辑不是那么复杂而我只运行一次,我意识到我可以将它嵌入到测试运算符的位置,但是当你需要在其他位置重用结果而不重新运行时,这并不理想.测试:
if long_running_command | grep -q trigger_word; then
: stuff
else
Run Code Online (Sandbox Code Playgroud)
到目前为止我唯一发现的是将代码作为命令替换的一部分进行分配:
status=$(long_running_command | grep -q trigger_word; echo $?)
if [ $status -eq 0 ]; then
: stuff
else
Run Code Online (Sandbox Code Playgroud)
即使这在技术上也不是一次性分配(尽管有些人可能认为可读性更好)但是必要的数值测试语法对我来说仍然很麻烦.也许我只是在强迫症.
我错过了一种更优雅的方式来为一个变量分配一个退出代码,然后在它上面进行分支吗?
简单的解决方案:
output=$(complex_command)
status=$?
if (( status == 0 )); then
: stuff with "$output"
fi
: more code
if (( status == 0 )); then
: stuff with "$output"
fi
Run Code Online (Sandbox Code Playgroud)
或者更优雅一点
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
Run Code Online (Sandbox Code Playgroud)
或者
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
Run Code Online (Sandbox Code Playgroud)