I want to check a particular string inserted by User to be checked against the values i already have in a ARRAY string using IF condition. Is this possible? if yes how to do that.
example :
i have a,b,c,d,e,f values in a array called values
i asked user to enter a value:
user entered b as a value
read uservalue
i have to check if the user entered value is present there inside my array using IF condition:
if [ $uservalue exist in ARRAY value ]
#!/bin/ksh
.
.
.
read ans
i=0
len=${#value[*]}
while [ $len -gt $i ]
do
if [ "${value[$i]}" = "$ans" ]
then
# Do your stuff here
fi
i=$(( $i + 1 ))
done
I recommend you to read one of the tutorials here:
#!/bin/bash
ARRAY=( a b c d e f )
read -p "Enter element : " K
FOUND=0
for E in ${ARRAY[@]}
do [ "$K" = "$E" ] && FOUND=1
done
echo -n "$K "; ((FOUND)) && echo "found" || echo "not found"
I use a flag here but if you only have to perform an action if found then use following code
#!/bin/bash
ARRAY=( a b c d e f )
read -p "Enter element : " K
for E in ${ARRAY[@]}
do if [ "$K" = "$E" ]
then echo "$K found"
fi
done