在命令行上有条件地设置变量

Ron*_*Ron 3 command-line shell

如果我的 Ubuntu 系统上的条件为真,我想设置一个变量。

这证明我的 if 语句是正确的:

$ (if [ 1 == 1 ]; then echo "hi there"; fi);
hi there
Run Code Online (Sandbox Code Playgroud)

这证明我可以设置变量:

$ a=1
$ echo $a
1
Run Code Online (Sandbox Code Playgroud)

这表明在 if 语句中设置变量不起作用:

$ (if [ 1 == 1 ]; then a=2; fi);
$ echo $a
1
Run Code Online (Sandbox Code Playgroud)

任何想法为什么?我所有的谷歌研究表明它应该像这样工作......

Kus*_*nda 10

(...)你的命令的一部分是你的问题。括号创建一个单独的子shell。子shell 将从其父shell 继承环境,但是一旦子shell 退出,其中设置的变量将不会保留其新值。这也适用于子 shell 内环境的任何其他更改,包括更改目录、设置 shell 选项等。

因此,删除子shell:

if [ 1 = 1 ]; then a=2; fi
echo "$a"
Run Code Online (Sandbox Code Playgroud)


ctr*_*lor 5

这证明在子shell中设置一个变量没有持久的效果

(if [ 1 == 1 ]; then a=2; fi);
echo $a
Run Code Online (Sandbox Code Playgroud)

产生

1
Run Code Online (Sandbox Code Playgroud)

与...一样

(a=2)
echo $a
Run Code Online (Sandbox Code Playgroud)

产生

1
Run Code Online (Sandbox Code Playgroud)

解决办法去掉括号。

if [ 1 == 1 ]; then a=2; fi;
echo $a
Run Code Online (Sandbox Code Playgroud)

产生

2
Run Code Online (Sandbox Code Playgroud)

或者如果你需要一个子外壳

(
  if [ 1 == 1 ]; then a=2; fi;
  echo $a
)
Run Code Online (Sandbox Code Playgroud)

产生

2
Run Code Online (Sandbox Code Playgroud)