Bash-当我试图得到 16 的平方时,这是错误的

标签 bash shell

我是 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/

相关文章:

Linux从零开始,Glibc-2.16 make报错

bash - 文本替换 bash 脚本

Git commit -m 不接受消息中的空格

linux - 如何在csh中定义 'alias'

regex - 使用 BASH 转换文件名中的最后一个连字符

linux - 如何在最小的 linux 安装上 "docker run"一个 shell session 并立即拆除容器?

linux - 在 (Bash/Docker RUN) 中以非交互方式自动回答 bash 命令的多个提示

python - 文本处理——两个文本文件 : read block lines from one file and append it after a string in another text file

linux - Linux Shell Scripts如何判断今天是星期天?

bash - 使用带有 "${parameter:-word}"参数扩展的引号