Re: Exit status or function return value?



In article <1177205275.078235.198930@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
heylow <vnr1995@xxxxxxxxx> wrote:

I ran this piece of script. I got the out put as follows:


$ ./pass1
5 + 10 = 15
10 - 2 = 8
10 / 2 = 5
5


My naive question: why $? returns 5, instead of the exit status of the
function calc, which must be 0. I know my assumption is wrong. But I
would like to know why it returns the way it did.

The "return $ans" command sets the function's exit status to $ans.


Thank you.



$cat pass1

#!/bin/sh
function cal()
{
n1=$1
op=$2
n2=$3
ans=0
if [ $# -eq 3 ]; then
ans=$(( $n1 $op $n2 ))
echo "$n1 $op $n2 = $ans"
return $ans
else
echo "Function cal requires atleast three args"
fi
return
}
cal 5 + 10
cal 10 - 2
cal 10 / 2
echo $?

--
Barry Margolin, barmar@xxxxxxxxxxxx
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***
.



Relevant Pages

  • Re: Exit status or function return value?
    ... My naive question: why $? ... instead of the exit status of the ... function calc, which must be 0. ... echo "Function cal requires atleast three args" ...
    (comp.unix.shell)
  • Re: Newbie Three
    ... echo "tesgform"; ... echo "suspected alien invasion case topic table"; ... echo "suspected alien invasion unknown group name"; ...
    (comp.lang.php)
  • Newbie Three
    ... echo "tesgform"; ... echo "suspected alien invasion case topic table"; ... echo "suspected alien invasion unknown group name"; ...
    (comp.lang.php)
  • [opensuse] Re: lack of flexibility of systemd
    ... # best to sudo first then run this script: ... # read the daemon's current config to get values...for defaults ... echo "Fatal error: Torrent data directories are not found" ...
    (SuSE)
  • ToDo list utility - suggestions/optimizations/refinements wanted
    ... For the past couple of days, I've been working on this todo list script and I'm really happy with the way it works, but wanted to post it here before I go any futher, in case anybody had suggestions for optimizations or style errors. ... echo "File written successfully." ...
    (comp.unix.shell)