Bash supress "Bad file descriptor" error message

Bash supress "Bad file descriptor" error message

当我尝试写入文件描述符时,如果另一端在写入之前关闭了 fd,我会收到以下错误消息:

./scr.sh: line 5: "$fd": Bad file descriptor

代码看起来或多或少像这样:

f(){
    local fd=$1
    sleep 2
    if command >&"$fd"; then
        echo test >&"$fd" 2>/dev/null
    fi
}

coproc sleep 1
f "${COPROC[1]}"

有没有办法检测文件描述符是否损坏或只是抑制错误消息?


编辑:所以 @terdon 建议的重定向到 /dev/null 命令的解决方案不起作用,因为错误是由 echo 生成的,它已经具有该重定向

选择 Stephane 的解决方案在运行 coproc 后复制 fds

编辑2:

So I just figured out that the solution for duplicating the fds didn't really work as expected. I was running the command in a subshell so i just noticed that the test whether the "closed" fd can be duplicated always succeed and when the fd is actually closed the shell exits. I have minified the example above to illustrate the issue:

coproc sleep 1
exec {fd_in}<&"${COPROC[0]}"-
exec {fd_out}>&"${COPROC[1]}"-

sleep 2

if { >&"${fd_out}"; } 2<> /dev/null; then
    echo test >&"$fd_out" 2>/dev/null
fi
echo done #never reaches here

Any ideas why this is happening?

相关内容