0

My goal is to run multiple processes using bash, then wait for user input (for instance, issuing a command of 'exit') and exiting out upon that command.

I have the bits and pieces, I think, but am having a hard time putting them together.

From what I saw, I can run multiple processes by pushing them to the back, like so:

./process1 &
./process2 &

I also saw that $! returns the most recently run process pid. Does this, then make sense:

./process1 &
pidA = $!
./process2 &
pidB = $!

From there, I am trying to do the following:

echo "command:"
read userInput

if["$userInput" == "exit"]; then
   kill $pidA
   kill $pidB
fi

does this make sense or am I not appearing to be getting it?

2 Answers 2

3

That looks good, although you'll probably need a loop on the user input part.

Note that you need to be careful with shell syntax. "pidA = $!" is not what you think; that's "pidA=$!". The former will try to run a program or command named pidA with arguments "=" and the PID of the last started background command.

Also note that you could use the "trap" command to issue the kill commands on termination of the shell script. Like this:

trap "kill $!" EXIT
Sign up to request clarification or add additional context in comments.

1 Comment

the spaces in the pidA = $! is what was causing it to error out
0

end code resulted in:

#!/bin/bash

pushd ${0%/*}
cd ../
mongoPort=12345
mongoPath="db/data"
echo "Starting mongo and node server"
db/bin/mongod --dbpath=$mongoPath --port=$mongoPort &
MONGOPID=$!
node server.js &
NODEPID=$!

while [ "$input" != "exit" ]; do
read input
   if [ "$input" == "exit" ]; then
      echo"exiting..."
      kill $MONGOPID
      kill $NODEPID
      exit
   fi
done

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.