从子Shell运行Shell命令

4

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

为了让它更清楚:

test.sh

#! /bin/bash

/bin/bash /* create child shell */

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

<shell-commandN>

exit 0

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

2个回答

2
你可以像这样设置成组。
#!/bin/bash
(
Command1
Command2
etc..
)

subshell() {
    echo "this is also within a subshell"
}

subshell

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

更新:如果我正确理解了你的评论,你希望使用 -c 选项和 bash,例如:

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

谢谢Anders。但是/bin/bash -c "Command1 && Command2...."不会显示一个新的子shell,从那里执行剩下的命令。 - nitin_cherian
@LinuxPenseur,如果你添加一个&符号的话,它就可以了 :) - Anders

1

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中执行。 - nitin_cherian
@LinuxPenseur:新进程是父进程的一个独立实例,因此我认为你放在 ( ) 之间的代码将由 /bin/bash 执行。 - Alberto Zaccagni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接