Bash Arrays

Bash Arrays

ExplaiBash arrays for a beginner in Linux

ยท

4 min read

Table of contents

Arrays are a useful data structure to store lists of items in Bash scripts. Here's how to define and use arrays in Bash:

Defining an array:

fruits=( apple banana orange )

Accessing array elements:

echo ${fruits[0]} # apple
echo ${fruits[1]} # banana

Checking the length of an array:

length=${#fruits[*]}
echo $length # 3

Looping through an array:

for fruit in ${fruits[*]} 
do
    echo $fruit
done
# apple
# banana
# orange

Adding elements to an array:

fruits[3]=kiwi
fruits[4]=mango

Replacing array elements:

fruits[0]=strawberry
echo ${fruits[0]} # strawberry

Extracting a subset of an array:

vegetables=("carrot" "potato" "beans")
fruits+=${vegetables[*]}

Some other useful array operations:

  • ${array[*]} - Expands to all elements of the array

  • ${array[@]} - Also expands to all elements

  • ${#array[*]} - Gets the length of the array

  • unset array[x] - Unsets the xth element of the array

  • unset array - Unsets the entire array

Arrays allow us to work with lists of items in a structured way in Bash scripts.


Examples

Here's an example of using ${array[*]} to expand all elements of an array:

fruits=( apple banana orange mango )

# Expand all elements, separated by spaces  
echo ${fruits[*]}
# apple banana orange mango

# Join all elements with commas    
echo "${fruits[*],}" 
# apple,banana,orange,mango,

# Loop through all elements
for fruit in ${fruits[*]}  
do
    echo $fruit
done
# apple  
# banana
# orange  
# mango

# Check length    
length=${#fruits[*]}
echo $length  
# 4

${array[*]} expands to all elements of the array, separated by the first character in IFS (default space).

It's equivalent to ${array[@]} which also expands all elements of the array.

The main differences are:

  • ${array[*]} is unaffected by shell metacharacters while ${array[@]} is not.

  • ${array[*]} undergoes word splitting while ${array[@]} does not.

So in situations where you want to preserve whitespace and metacharacters in array elements, use ${array[@]} instead of ${array[*]}.

The example above shows some common uses of ${array[*]}:

  • Expanding all elements separated by spaces

  • Joining all elements with a custom separator (comma here)

  • Looping through all elements in a for loop

  • Checking the length of the array

Hope this example helps clarify how to use ${array[*]} to expand all elements of an array in Bash! Let me know if you have any other questions.


Memoization

You can use arrays in Bash to increase the performance of deterministic functions (i.e. functions with the same input always produce the same output) by caching or memoizing the results.

Here's how it works:

  1. The first time a deterministic function is called with a given input, you:

    • Calculate the output as normal

    • Store the input and output in an associative array

  2. The next time the function is called with the same input, you:

    • Check if the input exists as a key in the associative array

    • If so, return the cached output from the array directly

    • This skips recalculating the output and returns the cached result immediately

This process is known as memoization, and it works by "memorizing" the results of expensive function calls and returning the cached result for the same input.

For example:

# Associative array to cache results
declare -A cache

function factorial() {
  n=$1

  # Check if result is cached
  if [[ -n ${cache[$n]} ]]; then
    echo ${cache[$n]}
    return
  fi

  # Calculate result
  res=1  
  for ((i=2; i<=n; i++)); do
    res=$((res*i))
  done

  # Cache result  
  cache[$n]=$res

  echo $res
}

The first time factorial(5) is called, it will calculate and cache the result (120). The next time it's called with the same input (5), it will return the cached result immediately.

This can significantly improve the performance of functions that perform expensive operations, especially for larger inputs where the time savings compound.

The downsides are:

  • Increased memory usage to store the cache

  • Cache invalidation - you must invalidate cached results when function logic changes

But for deterministic functions where performance matters, memoization using arrays is a useful technique in Bash.


Disclaim: This article is generated using AI. Read the entire series to learn Bash from AI with my questions. I ask so you do not have to. Just read and understand it. Be happy, learn and prosper. ๐Ÿ––

ย