2

我有下面的代码,并收到以下错误输出:

Enter your exam score
40
./if2.sh: line 6: 40: No such file or directory
Very well done. You have an A grade.

我在 CentOS 上使用 bash 4.1.2(1)。

#!/bin/bash
#This script demonstrates the if-then-elif format.

echo "Enter your exam score"
read exam_pct
if [ $exam_pct < 40 ]
then
    echo "Sorry, you have failed."
elif [ $exam_pct > 70 ]
then 
    echo "Very well done. You have an A grade."
else
    echo "Well done. You passed."
fi

这里有什么问题?

4

4 回答 4

4

代替

if [ $exam_pct < 40 ]

if (( exam_pct < 40 ))

看看比尔给出的链接。Unix shell 的历史充满了非直观的扩展。根据您的情况,Bash 应该可以安全使用。如果您对 shell 历史感兴趣,请查看http://www.in-ulm.de/~mascheck/bourne/

于 2013-06-18T02:24:59.867 回答
4

if [ $exam_pct < 40 ]应该if [ "$exam_pct" -lt 40 ]

if [ $exam_pct > 70 ]应该if [ "$exam_pct" -gt 70 ]

请始终引用您的变量。

查看更多详细信息 - http://tldp.org/LDP/abs/html/comparison-ops.html

于 2013-06-18T02:25:18.830 回答
3

详细说明您收到错误的原因:[不是特殊语法;它只是一个可执行文件(通常通过内置函数提供,尽管/usr/bin/[可能存在于您的系统中),按照惯例,它采用“]”作为其最后一个参数。

因此,当您编写 时[ $exam_pct < 40 ],您实际上是从[(理想情况下)两个参数(和 的内容)开始$exam_pct]以及名称通过40管道传输到其标准输入的文件的内容。

[ $exam_pct > 70 ]同样[ $exam_pct ],当您[执行70.

于 2013-06-18T02:51:52.643 回答
1

只是为了完整性:

if [ $exam_pct \< 40 ]

也有效

于 2013-06-18T05:33:28.663 回答