1

I have a bash menu that displays my 4 sprinkler zones. The commands are submitted to a background process.

I would like to add another menu option that kills any current background processes spawned by the script and turn off any GPIO pins. How can I do this?

This is my current code:

sprinklermenu.sh
-----------------
#!/bin/bash

MYITEMS="One Two quit"

select myitem in $MYITEMS
do
    case $myitem in
    One)
    echo "Zone 1"
    bash TestTimerInBackground.sh 1&
    ;;
    Two)
    echo "Zone 2"
    ;;
    quit)
    echo "Quit was selected"
    break;
    ;;
    esac
done

2 Answers 2

2

You have several alternatives, for example:

  1. Find the processes by name as @tlhingan suggested
  2. Save the PIDs of the started processes in a file
  3. Save the PIDs of the started processes in memory

I'm not sure how you plan to use this script. For example, should it be allowed to run ./TestTimerInBackground.sh 1 multiple times? (The same zone multiple times.).

Here's an example of collecting the PIDs in memory, and allowing a zone only once.

#!/bin/bash

options=("Zone One" "Zone Two" "Quit")
pids=()
zones=()

select item in "${options[@]}"
do
    case $REPLY in
    [12])
        num=$REPLY
        echo "Zone $num was selected"
        if [ "${zones[$num]}" ]; then
            echo Zone already running
        else
            zones[$num]=1
            ./TestTimerInBackground.sh 1 &
            pids+=($!)
        fi
        ;;
    3)
        echo "Quit was selected"
        for pid in ${pids[@]}; do
            kill $pid
        done
        break
        ;;
    esac
done
3

The general topic your are asking about (in case you need to Google more detailed info) is "job control."

Basically, shell commands ps and kill are what you will be playing with: ps lists processes, and kill kills them. You would have to parse ("have your script read and search") the output of ps in order to find the processes you are interested in, and then issue the kill command for them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.