我在shell脚本中遇到错误

时间:2015-12-30 21:33:54

标签: linux bash shell

我的代码:

echo "Please Enter The Purchase Price : "
read $PurPrice
echo "Please Enter The Selling Price : "
read $SellPrice

if [ "$PurPrice" -eq "$SellPrice" ]
        then
                echo "No Profit No Loss !"

elif [ "$PurPrice" -gt "$SellPrice" ]
        then
                loss=echo "$pp - $sp" | bc -l
                echo "There is loss of $loss."
else
        profit=echo "$sp - $pp" | bc -l
        echo "There is Profit $profit. "
fi

错误:

Please Enter The Purchase Price :                                                                                                 
': not a valid identifier `                                                                                                       
Please Enter The Selling Price :                                                                                                  
': not a valid identifier `                                                                                                         
    Newfile.sh: line 5: $'\r': command not found                                                                                      
    Newfile.sh: line 10: syntax error near unexpected token `elif'                                                                    
    'ewfile.sh: line 10: elif [ "$PurPrice" -gt "$SellPrice" ]   

1 个答案:

答案 0 :(得分:2)

您的代码存在很多问题。

  • 您的变量名称不一致(例如pp与PurPrice)
  • 只有在想要变量的值时才使用$(而不是读取的值) 例如)。
  • 您不能将字符串与整数测试运算符(-eq等)一起使用。
  • 您需要使用反引号来获取您运行的命令的输出。

这是功能代码:

#!/bin/sh
echo "Please Enter The Purchase Price : "
read PurPrice

echo "Please Enter The Selling Price : "
read SellPrice

if [ $PurPrice -eq $SellPrice ] ; then
        echo "No Profit No Loss !"
elif [ $PurPrice -gt $SellPrice ] ; then
        loss=`echo "$PurPrice - $SellPrice" | bc -l`
        echo "There is loss of $loss."
else
        profit=`echo "$SellPrice - $PurPrice" | bc -l`
        echo "There is Profit $profit. "
fi

但请注意,测试运算符(-eq -gt etc)仅适用于整数(输入1.99的价格会导致它失败)!

相关问题