2

I am working on a simple bash script. The script run command in sequence, like command1 then command2 and so on. However, at a certain time, I want to run a command then when this command is in process, I want to kill it. Let me explain with the help of following example:

#!/bin/bash
.
.
command24
kill $(pidof command24)
command26
.
.

When my script reaches command24, it takes about 5-7 minutes to complete. But After 2-3 minutes, I want to kill this command24 and move on to command 26. The problem is that, if this script is working in sequence then "kill" command cannot be executed before the completion of command24, but I want to initiate "kill" command when command24 is in process. I hope I am able to explain the scenerio well. Kindly guide me in this respect.

1 Answer 1

4

Just run the command in the background, tell your script to sleep for a few minutes and then kill it:

command24 &
sleep 3m
kill $(pidof command24)
command26

Or, even safer, use $! which will have the PID of the last command executed in the background:

command24 &
sleep 3m
kill $!
command26
3
  • 1
    Also the timeout GNU tool.
    – Kusalananda
    May 13, 2020 at 18:20
  • Wouldn't "kill $!" capture pidof "sleep", as it was the last command? May 13, 2020 at 18:58
  • 1
    @SalmanAhmed no, because sleep wasn't sent to the background. See the definition of $! in man bash: "! Expands to the process ID of the job most recently placed into the background".
    – terdon
    May 14, 2020 at 8:19

You must log in to answer this question.

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