Bash Run command for certain time?

I am making a bash script for my own use. How can I run a command for a certain time (like 20 seconds) and then terminate it? I have tried a lot of solutions but nothing works. I also tried the timeout command with no success. Please give me some solution for this.

For example: I want to run this command in a script and terminate it after 10 seconds

some command

Hm, that should do the trick:

xmessage "Hello World" &
pidsave=$!
sleep 10; kill $pidsave

xmessage provides a quick test case here (in your case the airodump command should go there); & puts it into background.

$! holds the PID of the last started process (see e.g. https://stackoverflow.com/a/1822042/2037712); the PID gets saved into the variable pidsave.

After some waiting (sleep), send a TERM signal to the process.


From the bash prompt you can use"

  • your_command & sleep 20; kill $!
  • Or use the timeout command: E.g. aptget install timeout and timeout -k 3m 14s your_command
  • Or use expect as explained here: https://unix.stackexchange.com/questions/43340/how-to-introduce-timeout-for-shell-scripting
  • or do it with perl: perl -e "alarm 10; exec @ARGV" "Your_command"
  • Or use this more cryptic solution: $COMMAND 2>&1 >/dev/null & WPID=$!; sleep $TIMEOUT && kill $! & KPID=$!; wait $WPID ( Source and explanation)

Another way is to use pgrep $pattern, or pkill $pattern; returns all the PIDs matching the given pattern, looking across all running processes on the machine. So to limit the scope of PIDs to only the ones you own, use: pgrep -P $mypid $pattern, or pkill -P$mypid $pattern

So to run a background process for a set length of time, your script would look something like this:

#!/bin/bash 
mypid=$$
run_something &
sleep $time_in_seconds
pkill -P $mypid something

Keep in mind that this will kill all processes with the same name pattern running under the current parent PID. So you could use this to start multiple processes, and kill them all simultaneously after a certain time.