开发者

Get the status returned from the process that just finished

开发者 https://www.devze.com 2023-04-12 09:29 出处:网络
I have a process that just finished (it was written in C) so I return a number in main to tell the status开发者_Go百科. How can I get this value from the process that just finished in the shell?It\'s

I have a process that just finished (it was written in C) so I return a number in main to tell the status开发者_Go百科. How can I get this value from the process that just finished in the shell?


It's easy: if you are in BASH or SH:

./c_program args...
echo "The retval is $?"

Please note: the variable $? contains the return value of the last run command.
So, you may want to store it in another variable before it changes:

myRet=$?
# do what you want with myRet

Command chaining   (see orangeoctopus answer for more info)

As you may know, a command is considered success if it returns 0,
while a value different than 0 indicates fome kind of failure.

In BASH, you can chain commands by using the && or || operators:

command1 && command2

 ↳ In the above, command2 will execute only if command1 succedded.

command1 || command2

 ↳ In the above, if the first command fails, the second will execute.


Try using echo $? directly after you run your command:

 $ ./myprogram
 $ echo $?

If you are trying to base a decision on the success of your command, you can use &&:

 $ ./myprogram && echo success

if you are trying to base a decision on the failure of your command, you can use ||:

 $ ./myprogram || echo failure

These two things are sometimes called "short circuiting"


solution is quite simple like: echo $?

0

精彩评论

暂无评论...
验证码 换一张
取 消