Cor*_*ein 5 shell scripting bash
以下脚本的行为与我预期的不同。在条件中的 '=' 周围添加空格使其按照我想要的方式执行,但它让我思考,它在条件中实际上在做什么?
#!/bin/bash
S1='foo'
S2='bar'
if [ $S1=$S2 ];
then
echo "S1('$S1') is equal to S2('$S2')
fi
echo $S1
echo $S2
Run Code Online (Sandbox Code Playgroud)
输出是:
S1('foo') is equal to S2('bar')
foo
bar
Run Code Online (Sandbox Code Playgroud)
S1 和 S2 的内容与它们分配的内容没有变化,因此 = 不执行分配。
记住这[
实际上是一个命令会很有帮助,通常也可以作为test
. 在 bash 中,它是一个内置函数,因此您可以使用man builtin
.
在该文件中:
test and [ evaluate conditional expressions using a set of rules
based on the number of arguments.
0 arguments
The expression is false.
1 argument
The expression is true if and only if the argument is not
null.
2 arguments
[...]
3 arguments
[...]
Run Code Online (Sandbox Code Playgroud)
二元规则是各种测试,三元规则一般是比较。当你在 = 周围放一个空格时,你会得到三个参数。但是当你把它们放在一起时,你会得到一个参数,正如你所看到的,如果这个参数不为空,它返回真。
在这种情况下,等于运算符不执行任何操作。
该表达式计算为实际字符串,其中和$S1=$S2
的值就位,实际上是字符串文字。S1
S2
foo=bar
由于该字符串文字不为空,因此语句
if [ "foo=bar" ];
Run Code Online (Sandbox Code Playgroud)
计算结果为 true,并且执行 if 语句的主体。