Shell function does not return values greater than

2019-02-26 10:44发布

   sum()
  {
     return $(($1+$2))

  }

   read a b
   sum $a $b
   echo $?

when we pass the value for a=255 and for b=36 the ans will be 35 why?

标签: linux shell
2条回答
Lonely孤独者°
2楼-- · 2019-02-26 11:12

As everybody pointed out, shell function cannot return a value greater that 255.

The common way to get values out of functions is to store them in a variable like so:

#! /bin/sh

sum() {
    local __res=$3
    local res=$(($1 + $2))
    eval $__res="'$res'"
}


sum 25000 5000 total

echo $total
查看更多
劫难
3楼-- · 2019-02-26 11:17

you are asking the shell to return the value.

The return value cannot be anything more than 255.

so when you add a=255 and b=36

 a + b = 255 + 36 = 291

but since it can only return a value from 0-255.

you subtract

result - return value = 291 - 256 (i.e the return value from 0-255) = 35.

hence your return value of 35.

查看更多
登录 后发表回答