Bash中的局部变量就像在Perl中一样?

时间:2014-05-12 14:56:25

标签: linux perl bash

接缝错误重复两次相同的字符串

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中执行局部变量,类似于Perl对{ ... }的处理方式?

2 个答案:

答案 0 :(得分:3)

对于您的具体示例,您可以使用子shell,它可以有效地本地化在其中分配的所有变量。

(
a='+::::::'
b="/etc/passwd"
grep -q "$a" "$b" || echo "$a" >> "$b"
)

答案 1 :(得分:0)

至少不在{ ... }

Advanced Bash-Scripting Guide表示 使用{ ... }创建的代码块会创建anonymous function,但所有变量仍将对脚本的其余部分可见。

这可能是chepner所述的错误术语。

man page of bash,称之为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.

以下是local variables中的更多信息及其范围。