使用var = $?测试命令的存储退出状态; [[$ var]]始终为true,无论是0还是1 [英] Testing a command's stored exit status with var=$?; [[ $var ]] is always true, whether 0 or 1

查看:95
本文介绍了使用var = $?测试命令的存储退出状态; [[$ var]]始终为true,无论是0还是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

The user wants to run the backup is emitted whether run_backup has 0 (success) or 1 (false)!

这是怎么回事?

(我的真实命令而不是truefalse的形式为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_backupzenity命令的退出状态这一事实,最简单的事情就是简单地使用&&zenity和您的函数组合为一个命令./p>


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]]始终为true,无论是0还是1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆