linux poison RSS
linux poison Email

Bash Script: Create & Use Associative Array like Hash tables

Before using Associative Array features make sure you have bash version 4 and above, use command "bash --version" to know your bash version.

Below shell script demonstrate  the usage of associative arrays, feel free to copy and use this code.

Associative arrays are created using declare -A name

Source: cat

# use -A option declares associative array
declare -A array

# Here, you can have some other process to fill up your associative array.

echo -n "Enter the ip address to know the hostname: "
read ipaddress

# Now you can use the associative array as hash table, (key,value) pairs.
echo "Hostname associated with the $ipaddress is: ${array[$ipaddress]}"

# You can also perform all the basic array operation.
# Iterate over Associative Arrays

#for hostname in "${array[@]}"; do
#       echo $hostname

Output: ./ 
Enter the ip address to know the hostname:
Hostname associated with the is: host4


Post a Comment

Related Posts with Thumbnails