简体   繁体   English

如何停止执行bash脚本?

[英]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. <CTRL> + <C>仅停止循环的后续迭代。

SIGINT does not terminate the 'following iteration of the loop'. SIGINT不会终止'循环的后续迭代'。 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. 而是,当您键入ctrl-C时,您将SIGINT发送到当前正在运行的tcpdump实例,并在循环终止后继续循环。 A simple way to avoid this is to trap SIGINT in the shell: 避免这种情况的一种简单方法是在shell中捕获SIGINT

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. 请注意,您需要在后台(附加运行tcpdump的&来启动它的线)这个工作。 If you have other background jobs running, you may need wait $! 如果您正在运行其他后台作业,则可能需要wait $! rather than just wait . 而不是wait

You should set the starting value of n at least 1 higher than 0. Example: 您应该将n的起始值设置为至少高于0的示例。示例:

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循环也可能更好:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在执行 bash 脚本期间用户键入时,如何停止显示文本? - How do i stop text showing up when user types during execution of bash script? 如何阻止信号杀死我的 Bash 脚本? - How do I stop a signal from killing my Bash script? 如何停止执行bash脚本,无论是否使用“source”调用它? - How can I stop execution of a bash script, whether or not it's invoked with “source”? 如何创建一个 bash 脚本,该脚本在执行脚本的同一行接受用户输入? - How do I create a bash script that accept user input on the same line as the execution of the script? 当 python 脚本失败时,如何停止执行 bash 脚本? - How do i halt execution of bash script when a python script fails? 编写bash脚本时,如何在退出脚本时停止退出会话? - Writing a bash script, how do I stop my session from exiting when my script exits? 如何在 bash 中创建一个“停止”脚本来关闭我之前使用不同的 bash 脚本打开的 gnome 终端选项卡? - How do I make a "stop" script in bash that closes gnome-terminal tabs that I had previously opened with a different bash script? Bash-防止脚本因错误而停止执行 - Bash - prevent script to stop execution on error 在 bash 中完成代码构建后如何停止执行? - How can I stop the execution when the codebuild is completed in bash? 在bash脚本中,如何将文本文件中包含的值提供给程序执行的开关? - In a bash script, how do I provide values contained in a text file to the switch of a program execution?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM