I have written a shell script run.sh
to trigger a few tasks based on the user’s input
#!/bin/bash echo "Please choose mode [1-3]: " read MODE case $MODE in 1) echo -n "Enter iteration: " read TIME echo "Start Updating ..." task 1 && task 2 && task 3 ;; 2) echo -n "Enter Seed Value: " read SEED echo "Start Updating ..." task 4 task 5 ;; 3) echo -n "Enter regression minimum value: " read MIN echo "Start Updating ..." task 6 ;; *) echo -n "Unknown option - Exit" ;; esac
The tasks 1,2 … 6 are php scripts that are run like /usr/bin/php task1.php $TIME
with $TIME as an argument for the php script etc…
The script runs fine when I type bash run.sh
but since tasks 1-6 takes a long time to complete I would like an option to run the script in background while I disconnect from the terminal. However if I run the script using bash run.sh &
I encountered an error like this:
Please choose mode [1-3]: 2 -bash: 2: command not found [5]+ Stopped bash run.sh
It seems like bash interpreted my input 2
as an argument not corresponding to read MODE
but instead of bash run.sh 2
which causes an error. I cannot change the script such that tasks 1-6 are run in the background like task 1 &
task 2 &
etc. because task 2 can only start running after task 1 is completed.
How can I accomplish what I want to do?
Advertisement
Answer
You could run all of those tasks sequentially in a background subshell
( task 1; task 2; task 3 ) &
Try this out with:
( echo "One"; sleep 1; echo "Two"; sleep 2; echo "Three"; sleep 3; echo "Done" ) &
You could also make this more script-looking:
( echo "One" sleep 1 echo "Two" sleep 2 echo "Three" sleep 3 echo "Done" ) &
Feel free to make use of the useful envar $BASH_SUBSHELL
( echo $BASH_SUBSHELL; ( echo $BASH_SUBSHELL ) )