Question

I have script with a loop:

until [ $n -eq 0 ]
do
    tcpdump -i eth0 -c 1000000 -s 0 -vvv -w /root/nauvoicedump/`date "+%Y-%m-%d-%H-%M"`.pcap
    n=$(($n-1))
    echo $n 'times left'
done

I want to understand how to stop execution of this script? <CTRL> + <C> only stops the following iteration of the loop.

Was it helpful?

Solution

SIGINT does not terminate the 'following iteration of the loop'. Rather, when you type ctrl-C, you are sending a SIGINT to the currently running instance of tcpdump, and the loop continues after it terminates. A simple way to avoid this is to trap SIGINT in the shell:

trap 'kill $!; exit' INT
until [ $n -eq 0 ]
do
    tcpdump -i eth0 -c 1000000 -s 0 -vvv -w /root/nauvoicedump/`date "+%Y-%m-%d-%H-%M"`.pcap&
    wait
    n=$(($n-1))
    echo $n 'times left'
done

Note that you need to run tcpdump in the background (append & to the line that starts it) for this to work. If you have other background jobs running, you may need wait $! rather than just wait.

OTHER TIPS

You should set the starting value of n at least 1 higher than 0. Example:

n=100
until [ "$n" -eq 0 ]
...

It's also a good practice to quote your variables properly.

Also it's probably better if you use a for loop:

for (( n = 100; n--; )); do
    tcpdump -i eth0 -c 1000000 -s 0 -vvv -w "/root/nauvoicedump/$(date '+%Y-%m-%d-%H-%M').pcap"
    echo "$n times left"
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top