Dash 下的脚本错误

Dash 下的脚本错误

为什么以下脚本使用 Dash (sh) 时会出现错误,而使用 Bash 时却可以正常运行?

我看不到错误

感谢您的帮助。

#!/bin/bash

# Calculate the length of the hypotenuse of a Pythagorean triangle
# using hypotenuse^2 = adjacent^2 + opposite^2

echo -n "Enter the Adjacent length: "
read adjacent

echo -n "Enter the Opposite length: "
read opposite

asquared=$(($adjacent ** 2))        # get a^2
osquared=$(($opposite ** 2))        # get o^2

hsquared=$(($osquared + $asquared)) # h^2 = a^2 + o^2

hypotenuse=`echo "scale=3;sqrt ($hsquared)"  | bc`  # bc does sqrt

echo "The Hypotenuse is $hypotenuse"

结果:

myname@myhost:~$ sh ./hypotenusa.sh

Enter the Adjacent length: 12

Enter the Opposite length: 4

./hypotenusa.sh: 12: ./hypotenusa.sh: arithmetic expression: expecting primary: "12 ** 2"


myname@myhost:~$ bash ./hypotenusa.sh

Enter the Adjacent length: 12

Enter the Opposite length: 4

The Hypotenuse is 12.649

我的 Ubuntu 版本是 13.04。

答案1

答案很简单,它dash不支持通过**运算符进行幂运算(这不是 POSIX 兼容的 shell 解释器的要求)。

你可以使用该实用程序检查特定脚本是否使用了此类“bashisms” checkbashisms,例如

$ cat > myscript.sh
#!/bin/sh

echo $((12 ** 2))

Ctrl+d

$ checkbashisms myscript.sh
possible bashism in myscript.sh line 3 (exponentiation is not POSIX):
echo $((12 ** 2))
$ 

答案2

**运算符无法被 sh 识别。sh(Shell 命令语言)是一种由POSIX 标准,而 bash 会改变有效 POSIX shell 脚本的行为,所以 bash 本身并不是一个有效的 POSIX shell。**指数运算符在 bash 2.02 版本中引入过。

资料来源:

在 bash 和 sh 中,^是将数字转换为另一个数字的默认运算符(请参阅man bc)。因此,您的脚本应如下所示:

#!/bin/bash

# Calculate the length of the hypotenuse of a Pythagorean triangle
# using hypotenuse^2 = adjacent^2 + opposite^2

echo -n "Enter the Adjacent length: "
read adjacent

echo -n "Enter the Opposite length: "
read opposite

asquared="($adjacent ^ 2)"        # get a^2
osquared="($opposite ^ 2)"        # get o^2

hsquared="($osquared + $asquared)" # h^2 = a^2 + o^2

hypotenuse=`echo "scale=3;sqrt ($hsquared)"  | bc`  # bc does sqrt

echo "The Hypotenuse is $hypotenuse"

相关内容