开发者

Bourne Shell: Graceful way to get exit status

Is there a more graceful way to do this (bourne shell)?

IsThereAnyApplesLeft
applesLeft=$?

Normally i开发者_开发知识库n c or java I would do:

applesLeft=IsThereAnyApplesLeft


Exit status is normally used implicit like this:

if IsThereAnyApplesLeft;then
   echo "Apples left"
fi


Try:

applesLeft=$(IsThereAnyApplesLeft > /dev/null)$?

And yes, you've to use $? there is no way to avoid it.


The two pieces of code are not directly comparable. Your bash example is creating a subprocess to run an executable called "IsThereAnyApplesLeft", waiting for that subprocess to finish and storing the exit code of the subprocess in the variable $? so that you can examine it and act accordingly.

That's actually quite a complex interaction and to do the same thing in C would require a considerable amount of code. You'd have to fork() a subprocess, have the parent wait4pid() on the child's pid, while at the same time in the child calling execl() on the file "IsThereAnyApplesLeft" to make it run. One of the benefits of using a shell scripting language is that it hides this sort of stuff from you.

By comparison, your C code snippet is just calling a C function and storing the result in a local variable. That would look like this in bash:

IsThereAnyApplesLeft()
{
        echo 498
}

applesLeft=`IsThereAnyApplesLeft`
echo "there are $applesLeft apples left."


What's not graceful about $??

According to the Advanced Bash Scripting Guide, there's no other way to obtain the exit code besides $? -- well, they don't list any other way to obtain it besides $?. If there was another way, it would have certainly been listed in their Exit Code section in the above link.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜