문제

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

IsThereAnyApplesLeft
applesLeft=$?

Normally in 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top