在Ctrl + C上,终止当前命令,但继续执行脚本


10

我有一个bash脚本,其中我执行一行,休眠一段时间,然后在tail -f日志文件中验证是否可以看到某种模式,按ctrl + c退出,tail -f然后移至下一行直到bash脚本完成执行:

到目前为止,这是我所做的:

#!/bin/bash


# capture the hostname
host_name=`hostname -f`


# method that runs tail -f on log_file.log and looks for pattern and passes control to next line on 'ctrl+c'

echo "==================================================="
echo "On $host_name: running some command"
some command here

echo "On $host_name: sleeping for 5s"
sleep 5

# Look for: "pattern" in log_file.log
# trap 'continue' SIGINT
trap 'continue' SIGINT
echo "On $host_name: post update looking for pattern"
tail -f /var/log/hadoop/datanode.log | egrep -i -e "receiving.*src.*dest.*"


# some more sanity check 
echo "On $host_name: checking uptime on process, tasktracker and hbase-regionserver processes...."
sudo supervisorctl status process


# in the end, enable the balancer
# echo balance_switch true | hbase shell

该脚本有效,但是我得到了错误,需要更改什么/我在做什么错?

./script.sh: line 1: continue: only meaningful in a `for', `while', or `until' loop

也可能与此页面的访问者相关:unix.stackexchange.com/questions/163561/…–
pestophagous

Answers:


10

continue关键字并不意味着不管你认为它的意思。这意味着继续循环的下一个迭代。循环之外毫无意义。

我想你在找

trap ' ' INT

由于您不希望在接收到信号后执行任何操作(除了杀死前台工作以外),因此不要在陷阱中放入任何代码。您需要一个非空字符串,因为空字符串具有特殊含义:它将导致忽略信号。


1
或者trap : INT
斯特凡Chazelas

1

由于出现错误trap 'continue' SIGINT。来自help trap

ARG是外壳程序收到信号SIGNAL_SPEC时要读取并执行的命令

因此,您的脚本会continue在接收SIGINT呼叫时尝试执行命令,但continue仅在循环中使用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.