Prashant Singh
Prashant Singh

Reputation: 21

How do I search an element in shell script

I have an array

declare -a fruits=("apple" "banana" "guava" "cherry" "mango" "litchi")

I need to write a shell script, it can take multiple arguments (comma separated). It should check each argument against the array- fruits in case argument doesn't match it should exit stating argument is not in array. It should return all the invalid arguments

E.g ./dummy.sh carrot,potato,cabbage

o/p: carrot,potato,cabbage not found in array

e.g 2 ./dummy.sh banana,mango o/p banana,mango found in list

Upvotes: 0

Views: 1783

Answers (1)

blackpen
blackpen

Reputation: 2424

#!/usr/bin/bash    
declare -a fruits=("apple" "banana" "guava" "cherry" "mango" "litchi")

IFS=, read -ra args <<< "$1"
for arg in "${args[@]}"
do
   #echo "Searching for $arg"
   found=0
   for fruit in "${fruits[@]}"
   do
      if [[ $fruit == $arg ]]; then found=1; break; fi
   done
   if [[ $found == 0 ]]; then echo "$arg is not found"; break; fi
done

Upvotes: 1

Related Questions