In Bash, an array is a variable that can hold multiple values. It allows you to store and access a collection of elements using a single variable name. Here’s how you can work with arrays in Bash:
- Array Declaration: You can declare an array by assigning values to it using parentheses and separating the elements with spaces. For example:
my_array=("apple" "banana" "cherry")
2. Accessing Array Elements: To access individual elements of an array, you use the syntax ${array_name[index]}
. The index starts from 0 for the first element. For example:
echo ${my_array[0]} # Output: apple
echo ${my_array[1]} # Output: banana
3. Array Length: You can get the length of an array using the ${#array_name[@]}
syntax. For example:
echo "Array length: ${#my_array[@]}" # Output: Array length: 3
4. Modifying Array Elements: You can modify individual elements of an array by assigning a new value to the desired index. For example:
my_array[2]="strawberry"
echo ${my_array[2]} # Output: strawberry
5. Iterating Over an Array:
You can iterate over all elements of an array using a loop. For example:
for element in "${my_array[@]}"; do
echo $element
done
6. Appending Elements to an Array: You can append elements to an array using the +=
operator. For example:
my_array+=("grape" "melon")
7. Removing Elements from an Array: To remove elements from an array, you can use the unset
command with the index of the element you want to remove. For example:
unset my_array[1]
These are some basic operations you can perform with Bash arrays. Arrays provide a convenient way to work with collections of data and enable you to store, retrieve, modify, and iterate over multiple values using a single variable.