首页 > 解决方案 > 使用 $(...) 获取子命令的错误代码

问题描述

在这段代码中:

echo hello > hello.txt
read X <<< $(grep hello hello.txt)
echo $?

$?指 read 语句的退出代码为 0。有没有办法知道是否grep失败(例如,如果hello.txt已被另一个进程删除)而不将readand拆分为grep两个语句(即先grep检查$?then read)。

标签: bashexit-code

解决方案


使用process substitution代替command substitution + here string

read X < <(grep 'hello' hello.txt)

这会让你1在使用echo $?.

PS:如果grep失败,它将在您的终端上写入错误。

如果要抑制错误,请使用:

read X < <(grep 'hello' hello.txt 2>/dev/null)

推荐阅读