Home > OS >  Bash: Running a script that runs another script as a separate process
Bash: Running a script that runs another script as a separate process

Time:06-22

I have a script that does stuff with an ID as a parameter, I want to make it accept multiple parameters and then duplicate itself so that each copy runs with its own parameter from the list. For instance, I run "script 1 2 3&", and I want to see the result as if I were to run "script 1&", "script 2&", and "script 3&".

I can launch a script inside a script using

MyName="${0##*/}"
bash ./$MyName $id

$id is basically the parameter I want to put in this script. I launch multiple of them; however, the scripts I launch from within the script get processed in a raw, one after another, not parallel. I tried adding '$' at the end after $id, did not work.

Is it possible to launch a script from a script so that they run as separate processes in the background as if I were to run multiple scripts with & myself from the terminal?

CodePudding user response:

This does what I think you want... with some dummy example code for the case of handling a single id.

If no parameters are given, it will give you Usage: output, if more than one parameter is given it will invoke itself as a background job, once for each of those parameters, and then wait for those background jobs to be finished.

If only one parameter is given, it will execute the workload for you.

A cleaner approach would probably be to do this in two scripts, one that is the launcher that handles the first two situations, and a second script that handles the work load.

#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Usage $0 <id1> ..." 1>&2
    exit 1
fi

if [ $# -gt 1 ]; then
    # Fire up the background jobs
    for myid in $*; do
        $0 $myid &
    done
    # Now wait for the background scripts to finish
    wait
    exit 0
fi

id=$1

echo "PID $$ ($id) - Hello world, on $(date)."
sleep 5

Example run:

$ ./myscript.sh 10 20 30 40 50; date
PID 8558 (10) - Hello world, on Tue Jun 21 22:22:10 PDT 2022.
PID 8559 (20) - Hello world, on Tue Jun 21 22:22:10 PDT 2022.
PID 8560 (30) - Hello world, on Tue Jun 21 22:22:10 PDT 2022.
PID 8561 (40) - Hello world, on Tue Jun 21 22:22:10 PDT 2022.
PID 8563 (50) - Hello world, on Tue Jun 21 22:22:10 PDT 2022.
Tue Jun 21 22:22:15 PDT 2022

The ; date at the end shows that the initial script doesn't return until all child processes are finished.

  • Related