在寻找匹配的第27行时:语法错误:意外的文件结束

时间:2016-05-25 04:09:46

标签: bash variables for-loop

我正在尝试使用for循环创建一个乘法表,但我不知道如何初始化变量以及读取变量是否需要在for循环中相同

Syntax:
#!/bin/bash
#multiplication table
#$#=parameter given to the script
#$i=variable in for loop
#$1=variable represents a valid number not zero
#$0=variable represents bash script name

echo "Enter number you want to multiply"
read varnumber
echo "This number: $varnumber has this multiplication result:

if [ $varnumber -eq 0 ]
then
echo "Error - Number missing from command line argument"
echo "Syntax : $0 number"
echo "Use to print multiplication table for a given number"
exit 1
fi

n=$varnumber
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$varnumber * $i = `expr $i \* $varnumber`"

2 个答案:

答案 0 :(得分:3)

for循环应该以done结束,所以:

for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$varnumber * $i = `expr $i \* $varnumber`"
done  #line added

这样做也没有害处:

n="$varnumber" 

并注意bash中不首选反引号(``)。请使用命令$()格式代替this原因。所以:

echo "$varnumber * $i = $(expr $i \* $varnumber)" # Used $() syntax.

查看obsolete in bash是什么。

事实上,如果你可以在没有expr的情况下完成工作,那就更好了,这是一个外部命令:

echo "$varnumber * $i = $((i * varnumber))" # Faster than the previous version

(感谢@ benjamin-w提出这个建议)

答案 1 :(得分:0)

执行上述操作的更简单的bash脚本如下所示:

#!/bin/bash

echo "Enter the number for which the multiplication table is desired."
read varname

if [ $varname -eq 0 ];
then
    echo "Error!! The multiplication of anything with 0 results to 0."
    exit 130        # Exit with CTRL + C
fi

for ((i=1; i<=10; i++)); # You can change 10 into any other number
                         # according to your requirement.
                         # Or substitute it with a variable (say N)
                         # which can be prompted to the user.
do
    product=$(expr $i \* $varname)  # Or use: `expr $i \* $varname`
    echo "$varname times $i = $product"
done

输出如下:

"Enter the number for which the multiplication table is desired."

如果我在提示时输入5,将打印以下内容:

5 times 1  = 5
5 times 2  = 10
5 times 3  = 15
5 times 4  = 20
5 times 5  = 25
5 times 6  = 30
5 times 7  = 35
5 times 8  = 40
5 times 9  = 45
5 times 10 = 50