代码之家  ›  专栏  ›  技术社区  ›  Tuomas Toivonen

bash命令替换+参数扩展

  •  2
  • Tuomas Toivonen  · 技术社区  · 6 年前

    我很困惑引用、参数和全局展开是如何在子shell中工作的。子shell命令行的引用和扩展是否总是发生在子shell进程的上下文中?我的测试 似乎 以确认这一点。

    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ ls
    a  b  c
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ echo "$(echo *)"
    a b c
    # The subshell expands the * glob
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ echo $(echo '*')
    a b c
    # The subshell outputs literal *, parent shell expands the * glob
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ echo $(echo "*")
    a b c
    # The subshell outputs literal *, parent shell expands the * glob
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ echo "$(echo '*')"
    *
    # The subshell outputs literal *, parent shell outputs literal *
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ foo=bar
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ echo "$(echo $foo)"
    bar
    # The subshell expands variable foo
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ echo $(echo '$foo')
    $foo
    # The subshell outputs literal $foo
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ echo $(echo "$foo")
    bar
    # The subshell expands variable foo
    
    Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell/test1/test
    $ echo "$(echo '$foo')"
    $foo
    # The subshell outputs literal $foo
    

    我说的对吗?是否存在这样的场景:父shell将在分叉前以某种方式处理或评估子shell命令行?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Charles Duffy    6 年前

    解析——因此,如何确定引用哪个内容——是如何发生的 之前 叉子。因为shell的分叉副本具有其父进程内存的copy-on-write实例,所以它还具有分析树,并从其父进程继承此信息。

    参数展开 $foo 在你的例子中)发生 之后 叉子。同样,内容 foo 第一个字符串拆分和glob是否展开以生成要传递到的参数列表? echo 在地下室里。然后那次地狱就开始了 回声 ,并且写入stdout的输出由父进程(原始shell)读取。

    命令替换结果的字符串拆分和全局扩展(由 回声 )在父进程中将其子进程的输出作为字符串读取之后,返回父进程。

    推荐文章