Last updated on November 2nd, 2022 at 10:41 am

An array is like a list of elements, you can refer to specific elements in an array with indices. For instance myarray[i] refers to the i th element in an array named myarray. Here i am using korn shell.

We can use the below shell script in order to search for an element and return a unique output if it is present in the array or not.

This script simply helps you to check whether a variable is present inside an array.

First initialize the array elements

myarray=('data1' 'data2' 'data3' 'data4')

Now create a script that will search whether a variable is present in an array or not.

if [[ " ${myarray[*]} " == *" $1 "* ]]; then
check_val=$1
echo "Found Element "$check_val
else
check_val=$1
echo "Did Not Find Element Named "$check_val
fi

$1 represent the first argument passed to the script.

Please find the complete script below.

#!/bin/bash
myarray=('data1' 'data2' 'data3' 'data4')
if [[ " ${myarray[*]} " == *" $1 "* ]]; then
check_val=$1
echo "Found Element "$check_val
else
check_val=$1
echo "Did Not Find Element Named "$check_val
fi

Save the script as check.sh

Usage

root@production-server:~# ./check.sh data1
Found Element data1
root@production-server:~# ./check.sh
Did Not Find Element Named
root@production-server:~# ./check.sh data4
Found Element data4
root@production-server:~# ./check.sh data6
Did Not Find Element Named data6

You can also add this shell script as a function and call it at any time you need. All you have to do is just enclose the script inside a function as shown

#!/bin/bash
function SOME_FUNCTION_NAME
{
myarray=('data1' 'data2' 'data3' 'data4')
if [[ " ${myarray[*]} " == *" $1 "* ]]; then
check_val=$1
echo "Found Element "$check_val
else
check_val=$1
echo "Did Not Find Element Named "$check_val
fi
}
#Call the function
SOME_FUNCTION_NAME "CheckThisElement"

Hope you have found this script useful.

Leave a Reply

Your email address will not be published. Required fields are marked *