bash - 使用 $(...) 获取子命令的错误代码
问题描述
在这段代码中:
echo hello > hello.txt
read X <<< $(grep hello hello.txt)
echo $?
$?
指 read 语句的退出代码为 0。有没有办法知道是否grep
失败(例如,如果hello.txt
已被另一个进程删除)而不将read
and拆分为grep
两个语句(即先grep
检查$?
then read
)。
解决方案
使用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)
推荐阅读
- python - 如何在直方图中拆分和堆叠条形图,仅对较低的条形进行孵化?
- javascript - 为什么我的图片库无法在移动设备上使用?
- c - ssl_accept() 在 c 中返回 SSL_ERROR_SYSCALL
- .net-core - .NET Core 嵌入式资源 + Gitlab:错误:没有要上传的文件
- scala - 如何使用 AspectJ 创建切入点来捕获多个参数组 Scala 函数
- mysql - 为什么要在数据透视表中定义外键为主键?
- php - PHP表单-图片上传
- webpack - 使用 webpack 编译单个 marko 组件
- python - 列表附加项上的 Python3 结果附加另一个项需要更多解释
- laravel - 记录大数据我收到内存限制错误