bash - Correct test for values in if statement in Bash
问题描述
What is the correct test for an if statement in bash. I am not certain if the second statement assigns a value or if it tests equivalency.
if [[ "$user_has_mfa" == "NO" ]]; then
.... do stuff...
fi
Or
if [[ "$user_has_mfa" = "NO" ]]; then
.. do stuff..
fi
解决方案
=
是条件表达式中字符串相等的标准运算符。命令中没有赋值运算符,因此和运算符[[ ... ]]
之间没有歧义;它们是等价的。=
bash
==
对于[
,=
是唯一的便携式运算符。==
被 允许bash
,但不允许,例如,被dash
。如果您关心可移植性,则只能[ "$user_has_mfa" = "NO" ]
接受。
在算术上下文中, 和 之间存在差异,因为允许赋值。for 是赋值,for 是相等测试。例如:=
==
=
==
$ x=0 # shell assignment
$ ((x = 3)) # arithmetic assignment
$ if (( x == 3 )); then echo "x is 3"; fi
x is 3
你也会遇到C 程序员需要担心的相同类型的“=
当我的意思是写的”错误。==
$ x=3
$ if ((x=4)); then echo "x equals 4"; fi
x equals 4
$ echo $x
4
推荐阅读
- javascript - ngfor 如何在 Angular 8 中设置动态函数?
- if-statement - 舵图中的 if 子句
- excel - 使用 Powershell 比较两个 EXCEL 文件以删除重复数据
- android - 当AllSuccess 或Firestore 中的批处理哪个更受欢迎?
- mysql - My_SQL 查询中的错误答案
- c# - .Net Framework 调试窗口不工作
- django - Django-REST 还是 Firebase?
- c# - 如何从 C#.Net 中的另一个窗体窗体继承窗体窗体
- python - 即使 Tensorflow < 1.6 也显示“非法指令(核心转储)”
- javascript - 为什么圆圈会附加在体外?D3.js