Is there a more graceful way to do this (bourne shell)?
IsThereAnyApplesLeft
applesLeft=$?
Normally in c or java I would do:
applesLeft=IsThereAnyApplesLeft
Is there a more graceful way to do this (bourne shell)?
IsThereAnyApplesLeft
applesLeft=$?
Normally in c or java I would do:
applesLeft=IsThereAnyApplesLeft
Try:
applesLeft=$(IsThereAnyApplesLeft > /dev/null)$?
And yes, you've to use $?
there is no way to avoid it.
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.
Exit status is normally used implicit like this:
if IsThereAnyApplesLeft;then
echo "Apples left"
fi
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."