Here are some common array operations in shell scripting:
-
Declaring an Array:
my_array=(value1 value2 value3) -
Accessing Elements:
echo ${my_array[0]} # Access the first element -
Getting the Length of an Array:
echo ${#my_array[@]} # Number of elements in the array -
Iterating Over an Array:
for element in "${my_array[@]}"; do echo $element done -
Adding Elements:
my_array+=(value4) # Append a new element -
Removing Elements:
unset my_array[1] # Remove the second element -
Slicing an Array:
echo ${my_array[@]:1:2} # Get elements from index 1 to 2 -
Finding Common Elements Between Two Arrays:
a=(1 2 3) b=(2 3 4) common=() for x in "${a[@]}"; do for y in "${b[@]}"; do if [ $x -eq $y ]; then common+=($x) fi done done echo "Common elements: ${common[@]}"
These operations are fundamental for manipulating arrays in shell scripts.
