Class 22 of 37 • Advance Shell Script \t\t\t\t

Arrays in Linux Shell Scripting - Indexed & Associative Arrays Guide

a shell variable is capable enough to hold single or multiple values.shell supports a different type of variable called "array variable" to store multiple values at the same time with giving a single name to variable.

Declare an Array


declare -a ARRAY_NAME
							

Defining Array Value


# Notice: no spaces around '=' in Bash variable assignment!
Array_Name[Index]=Value
# Or compound initialization:
Array_Name=( 'Val1' 'Val2' 'Val3' )
							

Example


declare -a myarray

# Correct syntax without spaces around '='
myarray[0]='Virtualhax Inc.'
myarray[1]='Veewom Technology'
myarray[2]='Quizer Studio'

echo ${myarray[0]}

# Output
# Virtualhax Inc.
							

Array Operations Cheatsheet

Operation Bash Syntax Description
Print Single Element echo "${myarray[1]}" Prints item at index 1.
Print All Elements echo "${myarray[@]}" Expands all items as separate words.
Array Length echo "${#myarray[@]}" Returns total number of elements.
Print All Indices echo "${!myarray[@]}" Returns all active index numbers.
Append Element myarray+=("New Item") Adds a new value at the end of the array.
Delete Element unset myarray[1] Removes element at index 1.

Iterating Through an Array in Bash


#!/bin/bash
# Loop through array elements

courses=('Linux' 'PHP' 'Python' 'C-Programming' 'HTML')

echo "Total Courses: ${#courses[@]}"
echo "----------------------------------------"

for course in "${courses[@]}"
do
    echo "Course: $course"
done
							

Associative Arrays (Hashmaps / Dictionaries in Bash)

Starting in Bash 4+, you can store key-value pairs using associative arrays (declared via declare -A):


#!/bin/bash
# Associative array demonstration

declare -A capitals

capitals["India"]="New Delhi"
capitals["USA"]="Washington D.C."
capitals["Japan"]="Tokyo"

echo "Capital of India is: ${capitals["India"]}"

# Loop through keys
for country in "${!capitals[@]}"
do
    echo "The capital of $country is ${capitals[$country]}"
done
							

Frequently Asked Questions (FAQ)

When wrapped in quotes, "${arr[@]}" expands each array item as a distinct separate quoted word (preserving spaces within items). In contrast, "${arr[*]}" concatenates all array elements into a single single-quoted string separated by the first character of $IFS.

Like C and Java, standard indexed arrays in Bash are zero-indexed, starting at index 0. Negative indices are also supported in modern Bash to count backwards (e.g. ${arr[-1]} accesses the last element).

Next Step in Your Linux Learning Path:

Parse positional parameters and build CLI utilities using getopts in Class 23: Command Line Arguments.

Continue to Class 23: Command Line Arguments → Previous: ← Loops | Full Syllabus

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!