Executing a program for X seconds then killing it: a simple bash script

I needed to execute a given command for a specified number of seconds on my Linux system. I wasn’t able to find a program for doing that so I ended up writing this little and simple Bash script:



echo "Executing: ${cmd} for $seconds seconds"

sleep $seconds

if [ -d /proc/$cmdpid ]
  echo "terminating program PID:$cmdpid"
  kill $cmdpid

If you save this into a file called run_seconds_then_exits.sh you use it with:

bash run_seconds_then_exits.sh "sleep 10" 5

The above will run the command sleep 10 for 5 seconds, then it will send a termination signal (SIGTERM) and the program will be terminated.

See any improvements to the script above? Please leave a comment below and let me know about it!

Scroll to Top