简体   繁体   English

Shell脚本中的Ctrl C

[英]Ctrl C in shell script

I've got a shell script with the following code; 我有一个带有以下代码的shell脚本;

#!/bin/bash
nfcapd -z -w -t30 -p 2055 -l /home/shane/Documents/nfdump

My problem is that when I execute the shell script, the command above executes over and over (it captures network traffic from a router), but I'd like for it to stop after 30 seconds. 我的问题是,当我执行shell脚本时,上面的命令一遍又一遍地执行(它捕获来自路由器的网络流量),但是我希望它在30秒后停止。 In the terminal I would just press Ctrl + c , is there a way of executing this command ( Ctrl + c ) after a certain time t? 在终端中,我只需要按Ctrl + c ,是否可以在一定时间t之后执行该命令( Ctrl + c )?

Use timeout 使用timeout

timeout 30 nfcapd -z -w -t30 -p 2055 -l /home/shane/Documents/nfdump

More info here 更多信息在这里

Put this statement after #!/bin/bash 将此语句放在#!/bin/bash

(sleep 30 ; kill -9 $$ )& (睡眠30;杀死-9 $$)&

See if it works in your case. 看看是否适合您的情况。

You may also kill the last job: 您可能还会杀死上一份工作:

#! /bin/bash
nfcapd -z -w -t30 -p 2055 -l /home/shane/Documents/nfdump &
sleep 30 ; kill %%
echo "nfcapd terminated"
exit 0

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM