Bash 用于查找阶乘的脚本
Bash script to find factorial
程序接受输入但显示以下错误,如何解决这些错误?
实际上,在第 7 行,您忘记了完成反引号。
[
不只是语法,它是一个命令,所以需要space来分隔从它的论点。
while [ $counter -le $number ]
# .....^....................^
确保验证 number
实际上只是数字。
其他一些评论:
- 使用
$(...)
而不是 `...`
-- 请参阅
https://github.com/koalaman/shellcheck/wiki/SC2006
了解更多详情。
- bash会做算术运算,不用喊
expr
。看
Arithmetic Expansion
和 Shell Arithmetic
在手册中。
还有一个算术条件构造(类似于
面向字符串的 [[...]]
条件构造)——参见
Conditional Constructs
并向下滚动到 ((...))
(没有直接的 link)。
我认为你需要在 [
之后和 ]
之前添加一个 space:
#!/bin/bash
echo "Enter the number to find it's factorial"
read number
total=1
counter=1
while [ $counter -le $number ];
do
total=` expr $counter \* $total`
counter=` expr $counter + 1`
done
echo $total
在Ubuntu这里工作:
$ ./factorial.sh
Enter the number to find it's factorial
5
120
程序接受输入但显示以下错误,如何解决这些错误?
实际上,在第 7 行,您忘记了完成反引号。
[
不只是语法,它是一个命令,所以需要space来分隔从它的论点。
while [ $counter -le $number ]
# .....^....................^
确保验证 number
实际上只是数字。
其他一些评论:
- 使用
$(...)
而不是`...`
-- 请参阅 https://github.com/koalaman/shellcheck/wiki/SC2006 了解更多详情。 - bash会做算术运算,不用喊
expr
。看 Arithmetic Expansion 和 Shell Arithmetic 在手册中。 还有一个算术条件构造(类似于 面向字符串的[[...]]
条件构造)——参见 Conditional Constructs 并向下滚动到((...))
(没有直接的 link)。
我认为你需要在 [
之后和 ]
之前添加一个 space:
#!/bin/bash
echo "Enter the number to find it's factorial"
read number
total=1
counter=1
while [ $counter -le $number ];
do
total=` expr $counter \* $total`
counter=` expr $counter + 1`
done
echo $total
在Ubuntu这里工作:
$ ./factorial.sh
Enter the number to find it's factorial
5
120