Linux流量控制退出到终端失败


0

我有一个流控制查询。当消息为:时HOSTNAME NOT ADDED IN /tmp/hosts EXITING,我想将脚本退出到终端,这是一条失败消息。

if grep -o 'abcdefgh01.was.db.dcbc' /tmp/hosts; then
  echo " HOSTNAME ADDED IN /tmp/hosts"
elif [ $?==1 ]; then
  echo " HOSTNAME NOT ADDED IN /tmp/hosts EXITING"; exit
fi|tee -a /tmp/log;

我尝试了上面的脚本,但失败时无法退出。我该如何解决?

Answers:


0

我认为问题在于,无论何时创建管道,shell都会将双方放入单独的进程中,即使它不需要。特别是,你的if- fi语句块在与shell脚本本身不同的进程中运行,所以你的exit语句只是终止if块 - 无论如何它都要结束 - 所以它什么也没做。

可能有一些方法可以解决这个问题 - 可能比以下更清楚 - 但我目前无法访问* nix系统来测试其中任何一个。一个应该工作的简单方法是使用标志文件:

exit_flag_file="/tmp/my_exit.$$"
rm –f "$exit_flag_file"
if grep -o 'abcdefgh01.was.db.dcbc' /tmp/hosts
then
    echo " HOSTNAME ADDED IN /tmp/hosts"
elif [ $?==1 ]
then
    echo " HOSTNAME NOT ADDED IN /tmp/hosts; EXITING"
    > "$exit_flag_file"
fi | tee -a /tmp/log
if [ -f "$exit_flag_file" ]
then
    exit
fi
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.