首页 > 解决方案 > 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==

对于[,=唯一的便携式运算符。==被 允许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

推荐阅读