What are some common array operations in shell scripting?

QuestionsQuestions8 SkillsProShell ArraysAug, 06 2025
0128

Here are some common array operations in shell scripting:

  1. Declaring an Array:

    my_array=(value1 value2 value3)
  2. Accessing Elements:

    echo ${my_array[0]}  # Access the first element
  3. Getting the Length of an Array:

    echo ${#my_array[@]}  # Number of elements in the array
  4. Iterating Over an Array:

    for element in "${my_array[@]}"; do
        echo $element
    done
  5. Adding Elements:

    my_array+=(value4)  # Append a new element
  6. Removing Elements:

    unset my_array[1]  # Remove the second element
  7. Slicing an Array:

    echo ${my_array[@]:1:2}  # Get elements from index 1 to 2
  8. 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.

0 Comments

no data
Be the first to share your comment!