LinuxQuestions.org

LinuxQuestions.org (http://www.linuxquestions.org/questions/index.php)
-   Linux - General (http://www.linuxquestions.org/questions/forumdisplay.php?f=1)
-   -   Elif Trouble (http://www.linuxquestions.org/questions/showthread.php?t=4175437378)

azurepenguin 11-15-2012 11:48 PM

Elif Trouble
 
When I run the following script, I only get output based on the first two digits and not the entire number.

For instance, if I input 134, the script will return a result for 13.

I would be grateful for any thoughts, ideas or help.

#!bin/bash
clear
#
echo "Age Check"
echo
echo -n "Enter customer's age: "
read age
echo
echo -n "Customer's age: "
echo $age
echo
if [ ${age} '<' \13 ]
then
echo "Allowed ratings: G '&' PG"
elif [ ${age} '<' \17 ]
then
echo "Allowed ratings: G, PG '&' PG-13"
elif [ ${age} '<' \21 ]
then
echo "Allowed ratings: G, PG, PG-13 '&' R"
elif [ ${age} '>' \20 ]
then
echo "Allowed ratings: G, PG, PG-13, R '&' X"
elif [ ${age} '>' \121 ]
then
echo "DEAD"
fi
echo
echo "End Script"

CroMagnon 11-16-2012 12:44 AM

The less-than and greater-than characters are for string comparisons, not numeric comparisons. Try -gt and -lt:

Code:

if [ ${age} -lt 13 ]

azurepenguin 11-16-2012 02:34 AM

That didn't correct the error

catkin 11-16-2012 09:56 AM

Using this corrected version of the script and entering 134 gives the expected result of the greater than 20 case. The greater than 121 case is unreachable because any age greater than 121 will be caught by the greater than 20 case. To fix, swap the order of the 121 and 20 tests.
Code:

#!/bin/bash
#
echo "Age Check"
echo
echo -n "Enter customer's age: "
read age
echo
echo -n "Customer's age: "
echo $age
echo
if [ ${age} -lt 13 ]
then
echo "Allowed ratings: G '&' PG"
elif [ ${age} -lt 17 ]
then
echo "Allowed ratings: G, PG '&' PG-13"
elif [ ${age} -lt 21 ]
then
echo "Allowed ratings: G, PG, PG-13 '&' R"
elif [ ${age} -gt 20 ]
then
echo "Allowed ratings: G, PG, PG-13, R '&' X"
elif [ ${age} -gt 121 ]
then
echo "DEAD"
fi
echo
echo "End Script"

BTW the { and } in ${age} are not wrong but are not necessary.

azurepenguin 11-17-2012 02:12 AM

Switching the arguments to put the -gt 121 first corrected the issue. Thank you.


All times are GMT -5. The time now is 09:17 AM.