Bash - when I try to get a square of 16, this is wrong

I am new to bash. I am writing a script to calculate the square of a number. When the number is at least 16, it is incorrect ... There is no short or long type for the shell. So what is the largest amount in the shell?

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

The code:

 #!/bin/bash square() { let "res=$1*$1" return $res } as=16 square $as result=$? echo $result exit 0 
+5
source share
1 answer

The return code from the process is limited to 8 bits (the remaining bits have meta-information like โ€œwas there a core of the dump?โ€ And โ€œdid it signal to kill the process?โ€), So you wonโ€™t be able to use this to get values โ€‹โ€‹that exceed 255 .

Thus, all 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 to capture the output, not 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 
+16
source

Source: https://habr.com/ru/post/1203355/


All Articles