Check if a variable is present in an array using shell script

Byadmin

Sep 16, 2014 ,

Last updated on October 25th, 2014 at 09:40 am

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)

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 element using set command.

set -A 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.

set -A 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

./check.sh data1

The output of the above command will be

Found Element data1

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

function SOME_FUNCTION_NAME
{
set -A 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. Please don’t forget to like us on our Facebook page. 🙂

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)

Leave a Reply

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

two × two =