Run shell command from child shell

匆匆过客 提交于 2019-12-12 16:15:25

问题


I have a Unix shell script test.sh. Within the script i would like to invoke another shell and then execute the rest of the commands in the shell script from the child shell and exit

To make it clear:

test.sh

#! /bin/bash

/bin/bash /* create child shell */

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

<shell-commandN>

exit 0

What my intention is to run the shell-commands1 to shell-commandN from the child shell. Kindly tell me how to do this


回答1:


You can setup in a group, like.

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

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

subshell

( and ) creates a subshell in which you run a group of commands, otherwise a simple function will do. I don't know if ( and ) is POSIX compatible.

Update: If I understand your comment correctly, you want to be using -c option with bash, like.

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



回答2:


From http://tldp.org/LDP/abs/html/subshells.html here is an example:

#!/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).


来源:https://stackoverflow.com/questions/4658128/run-shell-command-from-child-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!