To print all elements of an array in Bash using the echo command, you can use the following syntax:
-
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[@]}" -
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.
