【问题标题】:Run shell command from child shell从子 shell 运行 shell 命令
【发布时间】:2011-01-11 13:29:59
【问题描述】:

我有一个 Unix shell 脚本 test.sh。在脚本中,我想调用另一个 shell,然后从子 shell 执行 shell 脚本中的其余命令并退出

说清楚:

test.sh

#! /bin/bash

/bin/bash /* create child shell */

<shell-command1>
<shell-command2>
......

<shell-commandN>

exit 0

我的意图是从子 shell 运行 shell-commands1 到 shell-commandN。请告诉我如何做到这一点

【问题讨论】:

    标签: shell unix scripting


    【解决方案1】:

    你可以设置成一个组,比如。

    #!/bin/bash
    (
    Command1
    Command2
    etc..
    )
    
    subshell() {
        echo "this is also within a subshell"
    }
    
    subshell
    

    ( and ) 创建一个子shell,您可以在其中运行一组命令,否则一个简单的函数就可以了。我不知道 ( 和 ) 是否与 POSIX 兼容。

    更新:如果我正确理解您的评论,您希望将-c 选项与bash 一起使用,例如。

    /bin/bash -c "Command1 && Command2...." &
    

    【讨论】:

    • 感谢安德斯。但是/bin/bash -c "Command1 &amp;&amp; Command2...." 没有显示一个新的子shell,其余的命令应该从那里执行
    • @LinuxPenseur,好吧,如果你附加一个&amp; 就可以了:)
    【解决方案2】:

    来自http://tldp.org/LDP/abs/html/subshells.html 这里是一个例子:

    #!/bin/bash
    # subshell-test.sh
    
    (
    # Inside parentheses, and therefore a subshell . . .
    while [ 1 ]   # Endless loop.
    do
      echo "Subshell running . . ."
    done
    )
    
    #  Script will run forever,
    #+ or at least until terminated by a Ctl-C.
    
    exit $?  # End of script (but will never get here).
    

    【讨论】:

    • 但我需要命令/bin/bash。该命令无法删除。执行 /bin/bash 后,将创建一个新的 shell,我希望从新的 shell 执行其余命令
    • @LinuxPenseur:新进程是父进程的分离实例,所以我相信你放在( )之间的代码将由/bin/bash执行