Bash 获取命令的返回值并以此值退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43801947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:07:41  来源:igfitidea点击:

Bash get return value of a command and exit with this value

bash

提问by RomMer

I want to execute a command then get the return value of this command. when it's done i want to exit and give exit the return value of the previous command, the one i just executed. I already have this piece of code but it doesn't seem to work.

我想执行一个命令然后获取这个命令的返回值。完成后我想退出并给 exit 上一个命令的返回值,我刚刚执行的那个。我已经有了这段代码,但它似乎不起作用。

exec gosu user /var/www/bin/phpunit -c app
typeset ret_code
ret_code=$?
if [ $ret_code == 0 ]; then
    exit 0
fi

exit 1

how can i do it ? thanks

我该怎么做 ?谢谢

回答by jschnasse

I think your problem is that typesetitself creates a return value of 0. Try

我认为你的问题是它typeset本身创建了一个 0 的返回值。试试

gosu user /var/www/bin/phpunit -c app
ret_code=$?
return $ret_code

回答by chepner

First of all, execonly returns if it fails, so you'll never see a zero exit status.

首先,exec只有在失败时才返回,因此您永远不会看到零退出状态。

exec gosu user /var/www/bin/phpunit -c app
ret_code=$?
printf 'Error in execing gosu, %d\n' $ret_code
exit $ret_code

Note this error has nothing to do with gosu; if execreturns, it is because the shell was unable to even startgosu, not because gosuitself exited with an error.

请注意,此错误与gosu; 如果exec返回,那是因为 shell 甚至无法启动gosu,而不是因为gosu它本身以错误退出。

Perhaps you didn't mean to use exec, and simply want to run the command and wait for it to complete?

也许您不是有意使用exec,而只是想运行命令并等待它完成?

gosu user /var/www/bin/phpunit -c app
ret_code=$?
if [ $ret_code = 0 ]; then exit 0; fi
printf 'Error in execing gosu, %d\n' $ret_code
exit $ret_code

回答by Christopher Whitehead

Know it has been awhile, but here is more a one liner.

知道已经有一段时间了,但这里有更多的单线。

Something like this...

像这样的东西...

if [ $(gosu user /var/www/bin/phpunit -c app;echo $?) ]; then
    exit 0
fi

exit 1

Or even shorter...

或者更短...

return $(gosu user /var/www/bin/phpunit -c app;echo $?)