Skip to content
Advertisement

Executing bash shell script accepting argument and running in background

I have written a shell script run.sh to trigger a few tasks based on the user’s input

JavaScript

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:

JavaScript

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

JavaScript

Try this out with:

JavaScript

You could also make this more script-looking:

JavaScript

Feel free to make use of the useful envar $BASH_SUBSHELL

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement