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 -a ARRAY_NAME
# Notice: no spaces around '=' in Bash variable assignment!
Array_Name[Index]=Value
# Or compound initialization:
Array_Name=( 'Val1' 'Val2' 'Val3' )
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.
| 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. |
#!/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
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
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).
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