它错误地重复相同的string两次
grep -q '+::::::' /etc/passwd || echo '+::::::' >> /etc/passwd
但如果我这样做
{ local a='+::::::' local b="/etc/passwd" grep -q $a $b || echo $a >> $b }
bash抱怨
-bash: local: can only be used in a function
题
有没有办法在Bash中执行局部variables,类似于Perl如何处理{ ... }
?
对于您的具体示例,您可以使用一个子shell,它有效地本地化内部分配的所有变量。
( a='+::::::' b="/etc/passwd" grep -q "$a" "$b" || echo "$a" >> "$b" )
至少不要与{ ... }
。
高级Bash脚本指南指出用{ ... }
创建的代码块创建一个anonymous function
,但是脚本的其余部分仍然可以看到所有变量。
chepner指出,这可能是错误的术语。
bash的man页面 ,称之为group command
有以下说法:
{ list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recog‐ nized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter.
这里是一些更多的信息在本地变量和他们的范围。