在这段代码中:
echo hello > hello.txt
read X <<< $(grep hello hello.txt)
echo $?
Run Code Online (Sandbox Code Playgroud)
$?指的是读取语句的退出代码,它是 0。有没有办法知道grep失败(例如,如果hello.txt已被另一个进程删除)而不将read和拆分为grep两个语句(即,先grep检查$?然后检查read)。
使用process substitution代替command substitution + here string:
read X < <(grep 'hello' hello.txt)
Run Code Online (Sandbox Code Playgroud)
这将使您1在使用echo $?.
PS:如果grep失败,它会在你的终端上写一个错误。
如果要抑制错误,请使用:
read X < <(grep 'hello' hello.txt 2>/dev/null)
Run Code Online (Sandbox Code Playgroud)