Search code examples
bashmacoswebcam

How to run multiple instances of command-line tool in bash script? + user input for script


I am trying to launch multiple instances of imagesnap simultaneously from a single bash script on a Mac. Also, it would be great to give (some of) the arguments by user input when running the script.

I have 4 webcams connected, and want to take series of images from each camera with a given interval. Being an absolute beginner with bash scripts, I don't know where to start searching. I have tested that 4 instances of imagesnap works nicely when running them manually from Terminal, but that's about it.

To summarise I'm looking to make a bash script that:

  • run multiple instances of imagesnap.
  • has user input for some of the arguments for imagesnap.
  • ideally start all the imagesnap instances at (almost) the same time.

--EDIT--

After thinking about this I have a vague idea of how this script could be organised using the ability to take interval images with imagesnap -t x.xx:

  • Run multiple scripts from within the main script

or

  • Use subshells to run multiple instances of imagesnap

  • Start each sub script or subshell in parallel if possible.

  • Since each instance of imagesnap will run until terminated it would be great if they could all be stopped with a single command


Solution

  • the following quick hack (saved as run-periodically.sh) might do the right thing:

    #!/bin/bash
    
    interval=5
    start=$(date +%s)
    
    while true; do
        # run jobs in the background
        for i in 1 2 3 4; do
            "$@" &
        done
        # wait for all background jobs to finish
        wait
        # figure out how long we have to sleep
        end=$(date +%s)
        delta=$((start + interval - end))
        # if it's positive sleep for this amount of time
        if [ $delta -gt 0 ]; then
            sleep $delta || exit
        fi
        start=$((start + interval))
    done
    

    if you put this script somewhere appropriate and make it executable, you can run it like:

    run-periodically.sh imagesnap arg1 arg2
    

    but while testing, I ran with:

    sh run-periodically.sh sh -c "date; sleep 2"
    

    which will cause four copies of "start a shell that displays the date then waits a couple of seconds" to be run in parallel every interval seconds. if you want to run different things in the different jobs, then you might want to put them into this script explicitly or maybe another script which this one calls…