views:

148

answers:

4

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

IsThereAnyApplesLeft
applesLeft=$?

Normally in c or java I would do:

applesLeft=IsThereAnyApplesLeft
+2  A: 

Try:

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

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

codaddict
+1 Clever! And, assuming there's no output to stdout (or stderr), the redirection can be omitted.
Dennis Williamson
A: 

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.

Mark Rushakoff
That's only if you want to retain the exit status. If you are only going to use the status once, you can use it directly in the test `if IsThereAnyApplesLeft; then echo "yes"; else echo "no"; fi`
mpez0
+4  A: 

Exit status is normally used implicit like this:

if IsThereAnyApplesLeft;then
   echo "Apples left"
fi
Jürgen Hötzel
+1 Unless you actually need the actual exit code; but I don't typically want that outside of c
guns
pra
A: 

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."
joefis