0

在 bash 中,有一种方法可以创建一个函数流,如果出现错误,它将阻止下一个函数调用:

IE

function msg_ok {
      echo "$(date '+%Y%m%d_%H%M%S'): OK+: $1 $2" | tee -a "/tmp/log_me"
}
function msg_er {
      echo "$(date '+%Y%m%d_%H%M%S'): ERR: $1 $2" | tee -a "/tmp/log_me"
}
function msg_check {
     tail last_line_of_log | grep "ERR"
     exit 
}

function first {
       msg_check
       do_your_thing
       msg_er "nothing works"
       else
       msg_ok "go on to next"
}

function second {
       msg_check
       do_your_thing
       msg_er "nothing works 2"
       else
       msg_ok "go on to next 2"
}


first
second
third

我的意思是有没有办法以不同的顺序调用第一个第二个和第三个并停止如果之前调用了 msg_er ?

4

1 回答 1

1

这很容易。只需执行:

first && second && third

bash 中的&&操作符意味着作为第二个操作符的命令只有在作为第一个操作符的命令没有错误退出时才会执行。

不需要msg_check

您可能希望按如下方式更正您的脚本:

function msg_ok {
      echo "$(date '+%Y%m%d_%H%M%S'): OK+: $1 $2" | tee -a "/tmp/log_me"
}
function msg_er {
      echo "$(date '+%Y%m%d_%H%M%S'): ERR: $1 $2" | tee -a "/tmp/log_me"
}

function first {
  do_your_first_thing && { msg_ok "go on to next"; return 0 } || 
    { msg_er "nothing works"; return 1 }       
}

function second {
  do_your_second_thing && { msg_ok "go on to next 2"; return 0 } || 
    { msg_er "nothing works 2"; return 1 }       
}


first && second && third

但据我了解您的问题,我会这样做:

do_your_first_thing && do_your_second_thing && third
于 2020-05-14T10:05:50.807 回答