Почему следующий скрипт выдает ошибку при использовании Dash (sh), и то же самое работает при использовании Bash?
Я не вижу ошибки
Спасибо за вашу помощь. [ 114]
#!/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.
**
оператор не распознается по ш. sh (Shell Command Language) - это язык программирования, описанный стандартом POSIX , в то время как bash меняет поведение допустимых сценариев оболочки POSIX, поэтому сам bash не является допустимой оболочкой POSIX. **
оператор возведения в степень был введен в 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"
Ответ прост: dash
не поддерживает возведение в степень с помощью оператора **
(это не является обязательным требованием для POSIX-совместимого интерпретатора оболочки).
Вы можете проверить, использует ли конкретный сценарий такие «bashisms», используя утилиту checkbashisms
, например
$ cat > myscript.sh
#!/bin/sh
echo $((12 ** 2))
Ctrl kbd> + d kbd>
$ checkbashisms myscript.sh
possible bashism in myscript.sh line 3 (exponentiation is not POSIX):
echo $((12 ** 2))
$