Check if array contains value in shell script

Here is simple bash script to check if array contains value . We can iterate over array and check if value is exist or not but we can also check in if condition if array contains value or not.

  1. Use this solution, If array value doesn’t contains the space.
if [[ " ${arr[@]} " =~ " ${val} " ]]; then
    # put you commands here when array contains a value
fi

if [[ ! " ${arr[@]} " =~ " ${val} " ]]; then
    # commands here when array doesn't contains a value
fi

Example:
Use Case:
I have used this script to validate if correct task is passed or not in argument

#!/bin/bash
task=$1
arr=("task1" "task2" "task3")
if [[ " ${arr[@]} " =~ " ${task} " ]]; then
    echo "User has provided correct $task in argument"
    echo "Put your logic for $task"

else
   echo "Please pass correct task name in argument"
   echo "Correct values are"
   echo '("task1" "task2" "task3")'
fi

2. Use below solutions, if array contains space.

Here printf statement will prints each array value in a separate line.

The grep statement uses the special characters ^ and $ to find a line that contains exactly same value

if printf '%s\n' "${arr[@]}" | grep -q -P '^task1$'; then
    # ...
fi
(Visited 13,069 times, 1,138 visits today)