【问题标题】:What are these scope changes in a bash script doing?bash 脚本中的这些范围更改是做什么的?
【发布时间】:2021-09-03 13:44:19
【问题描述】:

如果你有这样的事情:

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

括号和大括号的含义是什么?这些构造称为什么?他们有什么属性?它们是用来做什么的?

【问题讨论】:

    标签: bash


    【解决方案1】:

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

    { echo $x } 错误,在结束 } 之前缺少一个 ;{ ... } 中运行的命令是在当前 shell 的上下文中运行的,通常用于需要重定向多个命令的输出时,例如

    {
        echo 1
        echo 2
    } > log
    

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

    【讨论】:

      【解决方案2】:

      re:(大括号)({...})...来自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 }) 中提供的 single 命令示例,抛开语法问题,没有多大意义(即,它与 echo $x 没有任何不同)。

      一个example from 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-02
        • 2016-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-24
        • 2011-08-26
        • 2015-03-04
        相关资源
        最近更新 更多