Bash arrays are used to store multiple values in a single variable.
Here’s a guide with examples on how to use arrays in Bash.
Declaring an Array
To declare an array in Bash, you can use the following syntax:
# Method 1: Using parentheses with space-separated values my_array=(value1 value2 value3) # Method 2: Using individual assignments my_array[0]=value1 my_array[1]=value2 my_array[2]=value3
Accessing Array Elements
To access a specific element in the array, use the index of the element:
echo ${my_array[0]} # Output: value1 echo ${my_array[1]} # Output: value2
Array Length
To find the length of the array, use the ${#array[@]} syntax:
echo ${#my_array[@]} # Output: Number of elements in the array
Iterating through an Array
You can loop through the elements of an array using a for loop:
# Iterate through the array elements for item in "${my_array[@]}" do echo $item done
Adding Elements to an Array
To add elements to an array, you can use various methods:
# Method 1: Append elements using parentheses my_array+=(value4 value5) # Method 2: Assign a value to a specific index my_array[3]=value4 my_array[4]=value5
Removing Elements from an Array
To remove elements from an array, you can unset specific indexes:
unset my_array[2] # Removes the element at index 2
Example
Here is an example that should help you understand how to use arrays in Bash and perform various operations on them.
# Declare an array fruits=(Apple Orange Banana) # Access elements echo "First fruit: ${fruits[0]}" # Output: Apple echo "Number of fruits: ${#fruits[@]}" # Output: Number of elements # Loop through the array elements for fruit in "${fruits[@]}" do echo "Fruit: $fruit" done # Add elements to the array fruits+=(Grapes) fruits[3]="Pineapple" # Remove an element unset fruits[1] # Removes 'Orange' # Print the updated array echo "Updated array:" for fruit in "${fruits[@]}" do echo "Fruit: $fruit" done
Leave a Reply