bash脚本中的作用域变化是什么?



如果你有这样的内容:

#!/bin/bash
(
x=foo
{ echo $x }
)

括号和大括号的意义是什么?这些构念被称为什么?它们有什么特性?它们是用来做什么的?

用圆括号括起来的(...)命令在子shell中运行。它们从父shell继承环境,但它们所做的任何更改都不会传播回父shell。

{ echo $x }错误,闭合}前缺少;。在{ ... }中运行的命令是在当前shell的上下文中运行的,它通常用于当您需要重定向几个命令的输出时,例如

{
echo 1
echo 2
} > log

注意,如果有换行符,则不需要最后的;

re: the(花括号)({...})…bash的手册页:

{ list; }
list is simply executed in the current shell environment.  list  must  be  termi‐
nated 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 recognized.  Since they do not cause a word break, they must be separated from
list by whitespace or another shell metacharacter.

所提供的单个命令在花括号内({ echo $x })的示例,撇开语法问题不谈,没有多大意义(即,它与echo $x没有任何不同)。

一个来自linux.com的例子:

$ { echo "I found all these PNGs:"; find . -iname "*.png"; echo "Within this bunch of files:"; ls; } > PNGs.txt
# or
$ { echo "I found all these PNGs:"
find . -iname "*.png"
echo "Within this bunch of files:"
ls
} > PNGs.txt

这里,{...}将所有输出分组在一起,因此只需要一个> PNGs.txt就可以将所有4x命令的输出发送到文件PNGs.txt

如果没有{...},您将需要:

$ echo "I found all these PNGs:"     >  PNGs.txt
$ find . -iname "*.png"              >> PNGs.txt
$ echo "Within this bunch of files:" >> PNGs.txt
$ ls                                 >> PNGs.txt

对于下面的一组命令,(...){...}生成相同的结果(所有输出都发送到文件PNGs.txt)…

{ echo "I found all these PNGs:"; find . -iname "*.png"; echo "Within this bunch of files:"; ls; } > PNGs.txt
( echo "I found all these PNGs:"; find . -iname "*.png"; echo "Within this bunch of files:"; ls; ) > PNGs.txt

…第二个选项会导致生成子shell的额外开销。

通过下面的例子,我们可以看到在当前/父shell中执行和在子shell中执行的不同效果:
$ { x=5 ; }           # defined in current/parent shell
$ ( x=7 ; )           # defined in subshell, not visible to parent; `;` is optional
$ echo $x
5

最新更新