如何从tail -f返回到底层脚本

Cai*_*der 5 ksh aix

我有一个ksh脚本,tail -f用于查看日志文件。

如何终止tail进程并继续执行底层脚本?

我在 AIX 7.1 上运行它。
- - - - - - - - - - - - - - - - - - - - - - -编辑 - - -------------------------------
根据吉尔斯的回答,我在我的脚本中尝试了这个:

trap 'echo "tail process terminated!"' 2
tail -f mylog.log
trap - 2
Run Code Online (Sandbox Code Playgroud)

现在执行tail命令后,然后按CTRL + C,tail进程被终止,我的脚本继续运行。但新的问题是,当我再次按下 CTRL+C 时,我的脚本不会退出。任何人都可以帮忙吗?

Gil*_*il' 2

的要点tail -f是永远运行直到被明确杀死,所以你必须安排杀死它。

如果有某种逻辑决定何时tail终止进程,请获取进程 IDtail并安排在需要时触发其终止。例如,如果你想在一分钟后杀死它:

tail -f file.log &
tail_pid=$!
sleep 60
kill $tail_pid
do_more_stuff
Run Code Online (Sandbox Code Playgroud)

tail如果您想在用户按Ctrl+时终止但不终止 shell 脚本C请捕获SIGINT信号。tail您需要将陷阱设置为非空字符串(任何非空值都可以,甚至是空格),因为空字符串会导致子进程以及调用 shell忽略 SIGINT 。

trap : INT       # set a signal handler for SIGINT that does nothing
tail -f file.log
do_more_stuff    # executed when tail is killed, e.g. by the user pressing Ctrl+C
trap - INT       # reset SIGINT to killing the script
Run Code Online (Sandbox Code Playgroud)