如果管道中的任何进程以非零退出,则捕获

时间:2018-04-21 19:54:24

标签: bash shell pipe

我有这段代码:

   ql_timeout=2500 ql_write_and_keep_open | nc localhost "${ql_server_port}" | while read response; do
         echo "response from server: $response";
         if [[ "$response" == "released" ]]; then
            echo "quicklock: Lock was released.";
            return 0;
         fi
   done || {
       >&2 echo "quicklock: could not release lock.";
       return 1;
    }

发生的事情是第一个proc ql_write_and_keep_open将超时,管道将关闭。

如果任何进程以非零退出,我想我想抓住它,有没有办法做到这一点?

我也不确定是否使用:

done || { ... };

也是正确的语法。我知道,while read进程发生在子shell中。

1 个答案:

答案 0 :(得分:0)

这些答案非常好: https://unix.stackexchange.com/questions/14270/get-exit-status-of-process-thats-piped-to-another

我认为这基本上就是我想做的事情:

(
   set -o pipefail;

   ql_node_value="$json" ql_to=2500 ql_write_and_keep_open | nc localhost "${ql_server_port}" | while read response; do
     echo "response from server: $response";
     return 0;
     if [[ "$response" == "released" ]]; then
        echo "quicklock: Lock was released.";
        return 0;
     fi
   done;
 )

 exit_code=$?

 if [[ ${exit_code} -eq 0 ]]; then
    echo "quicklock: lock was released!";
 fi

 echo "quicklock: could not release lock."  >&2 ;
 return 1;