Skip to content
Advertisement

I’m getting errors in my shell script

MY CODE :

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

THE ERRORS :

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" ]   

Advertisement

Answer

Your code has lots of issues.

  • You were not consistent in your variable names (e.g. pp vs. PurPrice)
  • You only use $ when you want the value of a variable (not on read’s for example).
  • You can’t use strings with the integer test operators (-eq and so on).
  • You need backticks to get the output of commands you run.

Here is functional code:

#!/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

but note that the test operators (-eq -gt etc) only work on integers (entering a price like 1.99 will cause it to fail)!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement