Search code examples
bashshelltcpdump

How do I stop execution of bash script?


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.


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.