Bash布尔测试 [英] Bash Boolean testing

查看:43
本文介绍了Bash布尔测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个标志设置为true,另一个标志设置为false,我正在尝试运行代码块.即

I am attempting to run a block of code if one flag is set to true and the other is set to false. ie

var1=true
var2=false
if [[ $var1 && ! $var2 ]]; then var2="something"; fi

由于无法评估我所期望的方式,因此我编写了其他几个测试用例,并且很难理解如何评估它们.

Since that did not evaluate the way that I expected I wrote several other test cases and I am having a hard time understanding how they are being evaluated.

aa=true 
bb=false
cc="python"
if [[ "$aa" ]]; then echo "Test0" ; fi
if [[ "$bb" ]]; then echo "Test0.1" ; fi
if [[ !"$aa" ]]; then echo "Test0.2" ; fi
if [[ ! "$aa" ]]; then echo "Test0.3" ; fi
if [[ "$aa" && ! "$bb" ]]; then echo "Test1" ; fi
if [[ "$aa" && ! "$aa" ]]; then echo "Test2" ; fi
if [[ "$aa" ]] && ! [[ "$bb" ]]; then echo "test3" ; fi
if [[ "$aa" ]] && ! [[ "$cc" ]]; then echo "test4" ; fi
if [[ $aa && ! $bb ]]; then echo "Test5" ; fi
if [[ $aa && ! $aa ]]; then echo "Test6" ; fi
if [[ $aa ]] && ! [[ $bb ]]; then echo "test7" ; fi
if [[ $aa ]] && ! [[ $cc ]]; then echo "test8" ; fi

当我运行前面的代码块时,我得到的唯一输出是

When I run the preceding codeblock the only output I get is

Test0
Test0.1
Test0.2

Test0
Test0.1
Test0.2

但是,我的期望是我会得到

however, my expectation is that I would get

Test0
测试1
Test3
Test5
Test7

Test0
Test1
Test3
Test5
Test7

我试图了解运行类似测试的最佳方法,但是我发现的大多数示例都以
的格式设置如果[["$ aa" == true]];
这不是我想做的.因此,我的问题是进行这种比较的最佳方法是什么?为什么我希望通过的几个测试用例根本不会通过?

I have tried to understand the best way to run similar tests, however most examples I have found are set up in the format of
if [[ "$aa" == true ]];
which is not quite what I want to do. So my question is what is the best way to make comparisons like this, and why do several of the test cases that I would expect to pass simply not?

谢谢!

推荐答案

没有任何运算符, [[]仅检查变量是否为空.如果是,则将其视为错误,否则将其视为正确.变量的内容无关紧要.

Without any operators, [[ only checks if the variable is empty. If it is, then it is considered false, otherwise it is considered true. The contents of the variables do not matter.

这篇关于Bash布尔测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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