Joh*_*ith 3 command-line bash scripts
尝试四处搜索并找不到我的问题的直接答案,因为那里的所有其他代码似乎都在做我正在做的事情。我正在做一个 shell 脚本练习来计算一个类的平均值,我已经使用我们的参考脚本做到了这一点,但是我收到了关于语法的错误(代码底部的错误)
#!/bin/bash
avg=0
temp_total=0
number_of_args=$#
# First see the sufficient cmd args
if [ $# -lt 2 ] ; then
echo -e "Oops! I need at least 2 command line args to calculate an average\n"
echo -e "Syntax: $0: number1 number2 ... numberN\n"
echo -e "Example:$0 5 4\n\t$0 56 66 34"
exit 1
fi
# now calculate the average of the numbers given on command line as cmd args for i in $*
do
# addition of all the numbers on cmd args
temp_total='expr $temp_total + $i '
done
avg='expr $temp_total / $number_of_args '
echo "The average of all the numbers is $avg"
Run Code Online (Sandbox Code Playgroud)
所以,我得到的错误是
./avg.sh: line 16: syntax error near unexpected token `do'
./avg.sh: line 16: `do'
Run Code Online (Sandbox Code Playgroud)
我在那个区域找不到任何特别错误的地方,所以我希望有人能帮助我!谢谢!
编辑:特别是,我尝试删除有关它们引起问题的可能性的评论,但无济于事。我也重新输入了该部分。我还尝试寻找不同的方法来处理该部分,但大多数平均脚本似乎以非常相似的方式处理它,所以我不知所措!
约一个意外的错误消息,抱怨do,因为你使用的是错误的:do在使用的保留字for,case,while和until循环。由于前面的评论以for i in $*我假设您只是忘记在那里添加换行符:
# now calculate the average of the numbers given on command line as cmd args
for i in $*
do
# addition of all the numbers on cmd args
temp_total='expr $temp_total + $1 '
done
Run Code Online (Sandbox Code Playgroud)
man bash/SHELL GRAMMAR/Compound Commands 解释了如何构建for和其他循环。如果你只是想循环每个参数bash也支持一个简短的形式,我将在这里将它与bash算术扩展结合起来:
# now calculate the average of the numbers given on command line as cmd args
for i
do
# addition of all the numbers on cmd args
temp_total=$((temp_total+i))
done
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10598 次 |
| 最近记录: |