linuxshellsubshell

How to execute new bash command inside shell script file?


How can I put the follow script to work properly?

1  #/bin/bash
2
3  # some commands
4
5  bash
6  # a lot of commands
7  # ...
8  exit
9  
10 bash
11 # A lot of other commands
12 # ...
13 exit
14 
15 exit 0

The problem is that when executing the script in shell, a new interactive bash shell is entered and the execution stopped right there waiting for standard input. As the sub-environment may not be BASH in practice, bash command in line 4 and 9 are just examples and that's why I need a new solution other than putting those commands into separate files and invoke.


Solution

  • This is the documented behaviour. If you execute a mere bash, you get an interactive shell. If you want to run several bash commands in a child process - which probably is what you want, since you tagged your question subshell, you write

    bash FILENAME
    

    where FILENAME is the name of the file which contains the commands. If you want to run several bash commands inside the current process, you write one of

    source FILENAME
    . FILENAME
    

    The differences between source and . are minor, and you find them described in the bash man page.

    If you want to run several commands in a child process, without putting them into a separate file, you can do it with

    (
       some command
       some other command
    )