【问题标题】:bash return code after reading for pipe读取管道后的bash返回码
【发布时间】:2014-11-28 10:09:33
【问题描述】:

如何返回 $code 作为此脚本的退出代码,而不是最后一个命令 rm "${fifo}" 的退出代码。

#!/bin/bash

fifo=myPipe
mkfifo "${fifo}"|| exit 1
{
    read code <${fifo}
} | {
    timeout 1 sleep 2
    timeoutCode=$?
    echo "${timeoutCode}" >${fifo}
}
rm "${fifo}"

【问题讨论】:

  • 是的,在第一组我会tail -f一个文件,在第二组我会grep匹配或超时,然后通过管道通知第一组,这将杀死尾巴,最后我想要一个退出代码显示我是否超时匹配

标签: bash shell unix pipe exit-code


【解决方案1】:

也许这可以达到您的目的:

这个答案有 2 个部分,您正在寻找:

  1. 设置 $?到任何所需的值
  2. 使用${PIPESTATUS[@]}数组获取流水线各个阶段的退出状态...

代码:

#!/bin/bash

return_code() { return $1; }    # A dummy function to set $? to any value

fifo=myPipe
mkfifo "${fifo}"|| exit 1
{
    read code <${fifo}
    return_code $code
} | {
    timeout 1 sleep 2
    timeoutCode=$?
    echo "${timeoutCode}" >${fifo}
}
ret=${PIPESTATUS[0]}
rm "${fifo}"
exit $ret

考虑到整个脚本的预期退出代码实际上是通过管道的第 2 阶段生成的,下面的逻辑也可以工作。

#!/bin/bash

    fifo=myPipe
    trap "rm $fifo" EXIT #Put your cleanup here...

    mkfifo "${fifo}"|| exit 1
    {
        read code <${fifo}
    } | {
        timeout 1 sleep 2
        timeoutCode=$?
        echo unused > ${fifo}
        exit $timeoutCode
    }

【讨论】:

  • 可以了,所以stage 0的退出码就是最后一个函数“return_code”的返回码?
  • 是的,${PIPESTATUS[0]} 将包含第一阶段的退出状态,这里恰好是$code...
猜你喜欢
  • 1970-01-01
  • 2015-10-08
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-12
  • 2016-02-02
相关资源
最近更新 更多