Hello,
I am doing bash and for that doing excersices. The folowing one asks for 3 numbers and is suppose to return the maximum. An error should be returned if on of the numbers is missing. I managed to solve it. Can you give me other ways or advices.
#!/bin/bash
#Date: 2010.10.19
#Ecrire un script qui prend en param�e trois entiers et qui affiche le plus grand. On affichera un message d'erreur s'il n'y pas pas trois arguments pass�sur la ligne de commande
echo "Entree trois entiers; separee par un espace";read numb1 numb2 numb3
MAX="0"
for i in $numb1 $numb2 $numb3 ; do
echo "$i"
if [ $MAX -lt $i ] ; then
MAX=$(echo $i)
fi
done
echo "Le plus grand nombre est: $MAX"
#END
for i in $numb1 $numb2 $numb3 ; do
echo "$i"
if [ `echo "$i" | awk '{ print (int($0)==$0)}'` == 0 ]; then
echo "$i" is not numeric
exit 1
fi
if [ $MAX -lt $i ] ; then
MAX=$(echo $i)
fi
done
echo "Entree trois entiers; separee par un espace";read numb1 numb2 numb3
MAX=0
counter=0
for i in $numb1 $numb2 $numb3 ; do
echo "$i"
counter=$(( ${counter} + 1 ))
if [ $MAX -lt $i ] ; then
MAX=$(echo $i)
fi
done
if [ ! $counter -eq 3 ]
then
echo "Please enter 3 numbers (not ${counter} numbers)"
else
echo "Le plus grand nombre est: $MAX"
fi
Added test for 3 values (uses array numbs) and test value entered is numeric. Errors printed to stderr and exit status set.
#!/bin/bash
#Date: 2010.10.19
#Ecrire un script qui prend en param�e trois entiers et qui affiche le plus grand. On affichera un message d'erreur s'il n'y pas pas trois arguments pass�sur la ligne de commande
echo "Entree trois entiers; separee par un espace";read -a numbs
MAX="0"
if [ ${#numbs[@]} -ne 3 ]
then
echo "Error: 3 numbers required" >&2
exit 1
fi
for i in ${numbs[@]} ; do
if [ $i -gt 0 ] 2> /dev/null || [ $i -le 0 ] 2> /dev/null
then
if [ $MAX -lt $i ] ; then
MAX=$i
fi
else
echo "Error: $i is not numeric" >&2
exit 2
fi
done
echo "Le plus grand nombre est: $MAX"