3

I am new to shell scripts. Say, I start a script like this. This runs for 3 days. So, I will start the script remotely through ssh and then close my local terminal.

start.sh

end=$((SECONDS+259200))
x=1
while [ $SECONDS -lt $end ]
do
    #Some command
done

How will I write a stop.sh to stop the script whenever I want to stop it? I can modify start.sh as well if needed.

1 Answer 1

8

A few ways:

Kill any instance of the script:

pkill -f start.sh

This will kill any process with start.sh in its command line, using pkill.

Kill a specific instance of the script:

Modify the script to save its PID somewhere:

#! /bin/bash
echo $$ >> /tmp/start_sh.pid
end=...

And tell stop.sh to kill the process with the PID there:

#! /bin/bash
kill $(cat /tmp/start_sh.pid) || echo "Process is not running."

This will kill all script.sh processes.

Communicate with start.sh

Tell start.sh to read from some file telling to quit:

#! /bin/bash
...
while [ $SECONDS -lt $end ]
do
    [[ $(cat ~/kill_start.txt) == "KILL" ]] && exit 1
    ...

And tell stop.sh to write "KILL" to that file:

#! /bin/bash   
echo "KILL" > ~/kill_start.sh

This will kill all instances of start.sh, when the next iteration of each script runs.

(Despite the name kill_start.sh is not a script.)

Use named pipes to communicate

Alternatively, you can run a background job in the script to watch for changes to ~/kill_start.sh:

#! /bin/bash
...
[[ -p ~/kill_script.sh ]] && mkfifo ~/kill_script.sh
(read -N 0 < ~/kill_script && [[ $REPLY == "KILL" ]] && kill 0) &

while [ $SECONDS -lt $end ]
do
    ...

In stop.sh, echo anything to ~/kill_script:

#! /bin/bash
echo anything at all

This will use mkfifo to make a named pipe. Then read will attempt to read from that pipe, and will wait until it gets any input at all, then proceed to exit. This should take effect almost immediately.


Use screen

With screen, you can start a shell via SSH, close your connection, and then resume it later. So you can start a screen session for the script, close your connection, go on holiday, come back, recall your screen connection and kill the script using CtrlC.

1
  • The pkill -f method didn't work for me.
    – ijt
    Mar 11, 2020 at 19:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .