Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash-when I try to get the square of 16, it's wrong

Tags:

bash

shell

I'm a beginner of bash. I write a script to compute the square of a num. When the num is not less than 16, it is wrong...There is no short or long type for shell. So what is the biggest number in shell?

1--1
2--4
3--9
::::
15-225
16-0
17-33
18-68

The code is:

#!/bin/bash
square() {
        let "res=$1*$1"
        return $res
}
as=16
square $as
result=$?
echo $result
exit 0
like image 871
tianzheng.jin Avatar asked Sep 25 '14 05:09

tianzheng.jin


1 Answers

The return code from a process is limited to 8 bits (the rest of the bits have meta-info like "was there a core dump?" and "did a signal kill the process?"), so you won't be able to use that to get values greater than 255.

So all the values will be modulo 256.

16^2 = 256 % 256 = 0
17^2 = 289 % 256 = 33
18^2 = 324 % 256 = 68
:
22^2 = 484 % 256 = 228
23^2 = 529 % 256 = 17

Instead, try capture the output rather than the return code:

#!/bin/bash
square() {
        let "res=$1*$1"
        echo $res        # echo answer rather than return
}
as=16
result=$(square $as)     # capture echo rather than $?
echo $result
exit 0
like image 180
paxdiablo Avatar answered Oct 20 '22 17:10

paxdiablo