我是 bash 的初学者。我写了一个脚本来计算数字的平方。当 num 不小于 16 时,就错了。。。shell 没有 short 和 long 类型之分。那么shell中最大的数是多少?
1--1
2--4
3--9
::::
15-225
16-0
17-33
18-68
代码是:
#!/bin/bash
square() {
let "res=$1*$1"
return $res
}
as=16
square $as
result=$?
echo $result
exit 0
最佳答案
进程的返回码限制为 8 位(其余位具有元信息,例如“是否有核心转储?”和“是否有信号终止了进程?”),因此您不会能够使用它来获得大于 255 的值。
所以所有的值都将以 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
相反, try catch 输出 而不是返回码:
#!/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
关于Bash-当我试图得到 16 的平方时,这是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26031220/