bin sh start multiple processes

1.4k views Asked by At

I am trying to start multiple processes for my development server by creating a #!/bin/sh file with shell commands in it.

E.g.:

#!/bin/sh

read -p "Start all servers? (Y/n)" answer
if test "$answer" = "Y"
then
    cd ./www/src; node ./index.js;
    cd ./www/; ./gulp;
    cd ./api/; nodemon ./init.js;
    cd ./api-test/; node ./index.js;
else
    echo "Cancelled."   
fi

Because for example nodemon will setup a watch process or node a http server process, the first command will start (cd ./www/src; node ./index.js;) and not continue to startup the other processes.

I can't figure out how to start all 4 processes independent of each other..

Anybody?

2

There are 2 answers

5
henfiber On BEST ANSWER

I would prefer to write some functions to spawn each process consistently:

  • One function called spawn_once will only run the command if it is not already running, therefore allowing only one instance
  • One second function called spawn will run the command even if it is already running (allow multiple instances)

Use the most appropriate for your use case

#!/bin/sh

# Spawn command $1 from path $2
spawn() {
    local cmd=$1; local path=$2
    ( [ ! -z "$path" ] && cd "$path"; eval "$cmd"; ) &
}


# Spawn command $1 from path $2, only if command $1 is not running
# in other words, run only a single instance
spawn_once() {
    local cmd=$1; local path=$2
    ( 
      [ ! -z "$path" ] && cd "$path"
      pgrep -u "$USER" -x "$cmd" >/dev/null || eval "$cmd"
    ) &
}


# Use spawn or spawn_once to start your multiple commands
# The format is: spawn "<command with args>" "<path>"
spawn "node ./index.js" "./www/src"
spawn_once "./gulp" "./www/"  # only one instance allowed
spawn "node ./index.js" "./api-test/"

Explanation:

  • ( [ ! -z "$path" ] && cd "$path"; eval "$cmd"; ) & : Change directory (if path argument was set) and run the command in a subshell (&), i.e. in the background, so it does not affect the current directory for other commands and does not block the script while the command is running.
  • spawn_once: pgrep -u "$USER" -x "$cmd" >/dev/null || eval "$cmd" : Check if the command has already been started with pgrep, otherwise (||) run the command.
2
Robert Navado On

You can use ampersand "&" to execute task in background

for example:

#!/bin/sh

read -p "Start all servers? (Y/n)" answer
if test "$answer" = "Y"
then
    cd ./www/src
    node ./index.js &
    cd $OLDPWD && cd ./www/
    ./gulp &
.........

else
    echo "Cancelled."   
fi