How to stop a command after a certain time in bash

Viewed 165

In bash, I'm running iftop tool with text output. It's a tool that is monitoring network and writting the results periodicaly in the standard output (by default the terminal but could be something else, a file). It's running in foreground until I stop it with ctrl + C

I would like to make it running for a certain period of time (1 minute for example), and then stop the process automatically

How can I make this in bash ?

Here is what I already tried:

sudo iftop -nNPt -L 100 -i wlp0s20f3 > iftop.out & pid=$!; sleep 20; sudo kill $pid

But, 1) it does not kill the process and 2) it does not redirect to the file

2 Answers

Using the timeout command in Linux should work, the syntax is below,

timeout [OPTION] DURATION COMMAND [ARG]...

I guess you can try putting everything after & in the next line. For this, you'll have to put the whole commands in a function in your .bashrc or in a script :

sudo iftop -nNPt -L 100 -i wlp0s20f3 > iftop.out &
pid=$!; sleep 20; sudo kill $pid
Related