Array

Shell Array Examples

Creating Arrays

You can create an array in a shell script by explicitly declaring an array or by setting values at specific indices.

Example 1: Explicit Declaration

# Declare an array with explicit elements
my_array=("apple" "banana" "cherry")

Example 2: Using Indices

# Declare an array and set values at specific indices
my_array[0]="apple"
my_array[1]="banana"
my_array[2]="cherry"

Accessing Array Elements

You can access elements of an array using the index of the element enclosed in curly braces.

# Access the first element
echo "${my_array[0]}"  # Outputs 'apple'

# Access all elements
echo "${my_array[@]}"  # Outputs 'apple banana cherry'

Passing Arrays to Functions

To pass an array to a function in Bash, you need to pass it as a series of arguments expanded at the time of call.

Example Function Definition

# Function to print all elements of an array
print_array() {
  echo "Array elements:"
  for element in "$@"; do  # Iterate over all arguments
    echo "$element"
  done
}

Calling the Function with Array

# Create an array
fruits=("apple" "banana" "cherry")

# Pass the array to function
print_array "${fruits[@]}"

Modifying Arrays

You can modify arrays by directly setting values at specific indices or by appending new elements.

# Modify an element
my_array[1]="blueberry"

# Append an element
my_array+=("date")

Summary

Arrays in shell scripting are versatile and can be used for managing lists of items. By understanding how to create, modify, and pass arrays to functions, you can effectively manage complex data structures within your scripts.