在shell (如Bash和Zsh )中,我们可以使用获得命令的标准输出。例如:
info=$(./run-a-program arg1 arg2)我们还可以从获得$?的退出代码。对于一些命令(如timeout )来说,它很有用。例如:
# run the program in 10 seconds
timeout 10s ./run-a-program arg1 arg2
if (( $? == 124 )) {
echo "Timeout!"
}那么,是否有一种同时获得退出代码和标准输出的方法?
发布于 2022-01-01 13:39:24
您仍然可以使用$?
info=$(./run-a-program arg1 arg2)
echo "run-a-program returned $?" 但是请注意,实际上很少需要直接引用$?。也许您希望编写如下代码:
info=$(./run-a-program)
if [ $? = 0 ]; then ...; fi但这可以写成:
if info=$(./run-a-program); then ...; fi有时,会使用除零/非零以外的特殊返回码,您可能需要执行case $? in,但这是您唯一需要显式引用$?的时间。摆脱查看$?的习惯;如果不这样做,代码就更容易维护。
https://stackoverflow.com/questions/70549056
复制相似问题