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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With