问题
Consider:
true; run_backup=$?
if [[ $run_backup ]]; then
echo "The user wants to run the backup"
fi
...and...
false; run_backup=$?
if [[ $run_backup ]]; then
echo "The user wants to run the backup"
fi
The user wants to run the backup is emitted whether run_backup has 0 (success) or 1 (false)!
What's going on here?
(My real command, instead of true or false, is of the form zenity --question --text "...").
回答1:
[[ $run_backup ]] is not a Boolean check; it fails only if its argument is an empty string (which neither 0 nor 1 is).
Since zenity returns 0 if you click OK, you want something like
[[ $run_backup -eq 0 ]] && echo "The user wants to run the backup"
or
(( run_backup == 0 )) && echo "The user wants to run the backup"
or
# 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"
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"
回答2:
The answer is yes, because neither 0 nor 1 is NULL.
来源:https://stackoverflow.com/questions/58418286/testing-a-commands-stored-exit-status-with-var-var-is-always-true-w