从子shell运行shell命令

时间:2011-01-11 13:30:00

标签: shell unix scripting

我有一个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。请告诉我如何做到这一点

2 个答案:

答案 0 :(得分:2)

您可以在群组中进行设置,例如。

#!/bin/bash
(
Command1
Command2
etc..
)

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

subshell

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

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

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

答案 1 :(得分: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).