Testing a command's stored exit status with var=$?; [[ $var ]] is always true, whether 0 or 1

本小妞迷上赌 提交于 2020-07-30 04:12:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!