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.
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.