How to use if statement with "expr"
Hi everyone
Im trying to write a simple script the can calculate the price of something, but when i run the script there is an error "expr: syntax error". here is my script #ex1 shirt=\$15.00 black=\$13.50 echo "Please enter how many shirt you want" read num1 echo echo "Please choose" echo "1 ---> Normal Shirt" echo "2 ---> black Shirt" read choice echo if [ $choice = "1" ]; then answer=`expr $num1 * $shirt` echo "$num1 * $shirt = $answer" elif [ $choice = "2" ]; then answer=`expr $num1 * $black` echo "$num1 - $num2 = $answer" else echo "invalid selection" fi Please anyone can help tell me what was missing in the script? sory for my poor english Thanks Tauatioti |
You are running into 2 problems:
1 - The * is special when using `expr $num1 * $shirt`. This causes the expr: syntax error You need to escape it: `expr $num1 \* $shirt` 2 - This is the biggest problem: Bash doesn't handle fractions that well. This may cause the following error: Code:
num=3 Code:
num=3 Code:
shirt=\$15.00 |
Hello druuna
Thanks for your quick reply, my first problem is solved, and i try your step to solve the second one (fraction) but it not working, any suggestion? Here is my script #exercise 3 clear shirt=15 black=13 echo "The price of the shirt is listed below" echo "Normal shirt \$15" echo "Black shirt \$13.5" echo "Please enter how many shirt you want" read num1 echo echo "Please choose" echo "1 ---> Normal Shirt" echo "2 ---> black Shirt" read choice echo if [ $choice == "1" ]; then answer=`expr $num1 \* $shirt` echo "$num1 * $shirt = $answer" echo "The Price is $answer dollars for $num1 Shirt" elif [ $choice = "2" ]; then total=$( echo "$black * $num1" | bc ) else echo "invalid selection" fi |
There are multiple errors/typo's in your code.
Have a look at this: Code:
if [ $choice == "1" ] |
you are right about my script.... i know that i solved my first problem using \* instead of *... but could you help on how i calculate decimal numbers
Thanks |
Have a look at these links:
- Perform arithmetic operations - Chapter 13. Arithmetic Expansion - Arithmetic Expressions in BASH |
I'll look at now, anyway thank you for your time
God bless you |
All times are GMT -5. The time now is 08:10 AM. |