Wednesday 28 March 2018

Shell script to search for a number in a list of positional parameters

#shell script to check whether the given number is present
n=$#
i=0
echo "Enter the number to check: \c"
read num
while [ $n -gt 0 ]
do
     i=`expr $i + 1`
     if [ $1 -eq $num ]
     then
           pos=$i
           break;
    fi
    shift
    n=`expr $n - 1`
done
if [ $n -gt 0 ]
then
     echo "Number $num is present in the list at position $pos"
else
     echo "Number not in the list"
fi


OUTPUT
csc@csc-SVE1513CYNB ~ $ sh present.sh 1 2 3 4 5
Enter the number to check: 5
Number 5 is present in the list at position 5

csc@csc-SVE1513CYNB ~ $ sh present.sh 1 2 3 4 5
Enter the number to check: 6
Number not in the list

No comments:

Post a Comment