variables in shell script is not calculated correctly
What is the mistake in my below shell script:
#!/bin/bash
total=0
for i in 1 2 3 4
do
echo -n "Enter Passenger Name: "
read pname
echo -n "Enter Car Number: "
read ncar
echo -n "Enter Amount: "
read amount
echo -n "Enter Distance Travelled: "
read dtravelled
total=$((total + dtravelled))
average=$(echo "$total 4" | awk '{print $1/$2}')
if test $dtravelled -gt 10000 -a $dtravelled -le 7000
then
bpassenger=$((business_pass + 1))
elif test $dtravelled -gt 7000 -a $dtravelled -le 5000
then
lpassenger=$((leisure_pass + 1))
else
opassenger=$((other_pass + 1))
fi
if test $i -eq 1
then
lname=$pname
low=$dtravelled
fi
if test $dtravelled -lt $low
then
lname=$pname
low=$dtravelled
fi
echo
done
echo "Total of distance travelled by the开发者_运维百科 passengers: $total"
echo "Average distance travelled by the passengers: $average"
echo "Number of business passengers: $bpassenger"
echo "Number of leisure passengers: $lpassenger"
echo "Number of other passengers: $opassenger"
echo "lowest distance travelled is $low by $lname."
***the below block is not calculated *** I always get empty output on this calculation
if test $dtravelled -gt 10000 -a $dtravelled -le 7000
then
bpassenger=$((business_pass + 1))
elif test $dtravelled -gt 7000 -a $dtravelled -le 5000
then
lpassenger=$((leisure_pass + 1))
else
opassenger=$((other_pass + 1))
fi
output:
bash mySript.sh
Enter Passenger Name: ahmad Enter Car Number: 9889 Enter Amount: 20 Enter Distance Travelled: 1100
Enter Passenger Name: sara Enter Car Number: 5214 Enter Amount: 300 Enter Distance Travelled: 1120
Enter Passenger Name: mohammad Enter Car Number: 9713 Enter Amount: 6 Enter Distance Travelled: 500
Enter Passenger Name: nora Enter Car Number: 98765 Enter Amount: 41 Enter Distance Travelled: 7500
Total of distance travelled by the passengers: 10220 Average distance travelled by the passengers: 2555 Number of business passengers: Number of leisure passengers: Number of other passengers: 1 lowest distance travelled is 500 by mohammad.
When writing
test $dtravelled -gt 10000 -a $dtravelled -le 7000
in normal mathematical notation, you see that it can never be true:
dtravelled > 10000 and dtravelled < 7000
⇔ 10000 < dtravelled < 7000
⇒ 10000 < 7000
⇒ False
Same for the other test with 7000 and 5000.
Adapt you logic. If you run into problems again, add set -x
to the beginning of your script or execute it with bash -x scriptFile.sh
. This will print the executed statements and variable contents, which will make debugging easier.
精彩评论