在 Bash 中,如何从嵌套在复杂语句中的命令捕获退出状态代码
我对 bash 的使用还比较陌生。我继承了这段代码,通过 SLURM 在 HPC 系统上运行命令:
CMD="srun -srunParam1 ... -srunParamN ./scriptToRun.sh -scriptParam1"
exec 5>&1
results=$(eval "${CMD}" | tee - >&5))
一切正常。
但是,我需要捕获 eval "${CMD}"
的退出状态,但不知道该怎么做。
最初,我将 exitStatus=$?
放在 results=...
命令之后;但是,我相信这是捕获为 results
变量赋值的状态,而不是 eval ${CMD}
的状态。
脚本继续处理中的输出$结果。我真的不明白为什么在这里打开文件描述符(或者,如何正确使用文件描述符)。但是,我会将其保存下来以供进一步研究/一个单独的问题。
编辑:我用文件描述符注释掉了这些位,并观察到脚本仍然有效,但 $results 不包含运行 $CMD 的输出 - 它只包含 $CMD 的后处理。
I'm relatively new to working with bash. I've inherited this bit of code to run a command via SLURM on an HPC system:
CMD="srun -srunParam1 ... -srunParamN ./scriptToRun.sh -scriptParam1"
exec 5>&1
results=$(eval "${CMD}" | tee - >&5))
That all works just fine.
But, I need to capture the exit status of just eval "${CMD}"
, and don't know how to do it.
Initially, I put exitStatus=$?
after the results=...
command; but, I believe that's catching the status of assigning a value to the results
variable, and not of eval ${CMD}
The script goes on to process the output that is in $results. I don't really understand why the file descriptor has been opened here (or, how to properly use file descriptors). But, I'll save that for further research/a separate question.
EDIT: I commented out the bits with the file descriptor, and observed that the script still works, but $results does not contain the output from running $CMD - it only contains the post-processing of $CMD.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Bash 有 PIPESTATUS :
请注意,在上面的代码中,我们正在检查在子 shell 中运行的命令的退出状态 (
$(...)
);无法访问父级中的 PIPESTATUS 。Bash has
PIPESTATUS
:Note that in the code above we are examining the exit status of a command that was run inside a subshell (
$(...)
); it would not work to accessPIPESTATUS
in the parent.获取状态的一种方法是将其保存在文件中:
One way to get status is to save it in a file :