How do we print all elements of an array in bash using the 'echo' command?

QuestionsQuestions8 SkillsProShell ArraysOct, 06 2025
0222

To print all elements of an array in Bash using the echo command, you can use the following syntax:

  1. Using ${array_name[@]}: This expands to all elements of the array as separate words.

    # Declare an array
    my_array=("apple" "banana" "cherry")
    
    # Print all elements
    echo "${my_array[@]}"
  2. Using ${array_name[*]}: This also prints all elements, but treats them as a single word when quoted.

    # Print all elements
    echo "${my_array[*]}"

Example:

Here’s a complete example demonstrating both methods:

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

# Print all elements using @
echo "Using @: ${fruits[@]}"

# Print all elements using *
echo "Using *: ${fruits[*]}"

Output:

Using @: apple banana cherry
Using *: apple banana cherry

Both methods will output the elements of the array, but the difference is in how they handle quoting and spacing. Using ${array_name[@]} is generally preferred when you want to preserve individual elements, especially if they contain spaces.

0 Comments

no data
Be the first to share your comment!