用 var=$?; 测试命令的存储退出状态[[ $var ]] 始终为真,无论是 0 还是 1 [英] Testing a command's stored exit status with var=$?; [[ $var ]] is always true, whether 0 or 1
问题描述
考虑:
true; run_backup=$?
if [[ $run_backup ]]; then
echo "The user wants to run the backup"
fi
...和...
false; run_backup=$?
if [[ $run_backup ]]; then
echo "The user wants to run the backup"
fi
用户想要运行备份
无论run_backup
是0(成功)还是1(假)都会发出!
The user wants to run the backup
is emitted whether run_backup
has 0 (success) or 1 (false)!
这是怎么回事?
(我真正的命令,而不是 true
或 false
,格式为 zenity --question --text "..."
).
(My real command, instead of true
or false
, is of the form zenity --question --text "..."
).
推荐答案
[[ $run_backup ]]
不是布尔检查;只有当它的参数是一个空字符串(既不是 0 也不是 1)时它才会失败.
[[ $run_backup ]]
is not a Boolean check; it fails only if its argument is an empty string (which neither 0 nor 1 is).
由于 zenity
如果单击确定"会返回 0,因此您需要类似
Since zenity
returns 0 if you click OK, you want something like
[[ $run_backup -eq 0 ]] && echo "The user wants to run the backup"
或
(( run_backup == 0 )) && echo "The user wants to run the backup"
或
# You need to negate the value because success(0)/failure(!=0) use
# the opposite convention of true(1)/false(0)
(( ! run_backup )) && echo "The user wants to run the backup"
<小时>
基于 run_backup
是原始问题中 zenity
命令的退出状态,最简单的方法是简单地使用 &&
将 zenity
和你的函数组合成一个命令.
Based on the fact that run_backup
was the exit status of a zenity
command in the original question, the simplest thing would be to simply use &&
to combine zenity
and your function into one command.
zenity --question --width=300 --text "..." && echo "The user wants to run the backup"
这篇关于用 var=$?; 测试命令的存储退出状态[[ $var ]] 始终为真,无论是 0 还是 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!