I have a script running in background like this:

nohup /tmp/a.sh &

If the script is running for more than 5 mins, I want to kill it.

-bash-3.2$ nohup /tmp/a.sh &
[1] 2518
-bash-3.2$ nohup: appending output to `nohup.out'

-bash-3.2$ ps -ef | grep /tmp/a.sh
ordev  2518 17827  0 15:24 pts/3    00:00:00 /bin/sh /tmp/a.sh
ordev  2525 17827  0 15:24 pts/3    00:00:00 grep /tmp/a.sh
-bash-3.2$ killall /tmp/a.sh  # killall not working like this
/tmp/a.sh: no process killed

If I use killall like below, it tries to kill all sessions running /bin/sh:

-bash-3.2$ killall sh /tmp/a.sh
sh(17822): Operation not permitted  # this pid associated with another process under root user. 
/tmp/a.sh: no process killed
[1]+  Terminated              nohup /tmp/a.sh .

Other than pkill -f, are there any alternatives that kill only the required script name?

  • 4
    timeout 5m urcommandhere
    – thrig
    Commented May 31, 2016 at 20:33
  • What's wrong with pkill -f?
    – Mikel
    Commented May 31, 2016 at 20:34
  • 3
    Also, note that nohup /tmp/a.sh & prints the pid. In your example, you could just do kill 2518 at the end.
    – Mikel
    Commented May 31, 2016 at 20:35
  • @Mikel : yes, pkill-f works fine, but just exploring how i can use killall.
    – dbain
    Commented May 31, 2016 at 20:40
  • Because killall is looking for something that matches the first arg for a process's CMD. For instance
    – Bratchley
    Commented May 31, 2016 at 21:19

2 Answers 2


Save the pid of the started process and save it to the file. Before spawning a new instance, check that the old has finished. Otherwise, kill it.

echo "Starting a new A instance"
nohup /tmp/a.sh &
echo "Writing A pid to file"
echo $! > /tmp/a_pid

Then you can check time and kill the script as:

if [ -f /tmp/a_pid ]; then
    echo "Trying to stop previous instance of proces A"
    kill $(cat /tmp/a_pid) || true
    echo "Removing A pid file"
    rm /tmp/a_pid

It's not necessary to kill by name. I recommend you save the PID of the script every time you run it, then call that PID from a file when you want to kill it. Like:

nohup /tmp/a.sh &
echo $! > a_pid

Then to kill it, do:

ps -9 ` a_pid`

Note $! gives the last command run which will be nohup nohup /tmp/a.sh &

  • ps? -9?? I'd suggest kill $!.
    – Mikel
    Commented Jun 6, 2016 at 23:58

You must log in to answer this question.

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