How to Print an Array in Bash? [5 Cases]

You can use the following 5 methods to print an array in Bash:

  1. To print the entire array:
    ${your_array[@ or *]}
  2. To print the array index, value, and type:
    declare -p <your_array>
  3. To print the array iteratively:
    for item in ${your_array[@]} do echo $item done
  4. To print the array in new lines:
    printf "%s\n" "${array_name[@]}"
  5. To print specific elements from an array:
    echo "${array[index_number]}"

The rest of the article represents an in-depth analysis of how to adopt these 5 methods to print arrays in Bash.

1. Print an Array in Bash Using Length Expression

Length expression ${array[@]} or ${array[*]} prints all the items of an indexed array located at the specified indices simply with the echo command.

Here’s how to print an indexed array in Bash using the length expressions ${array[@]} and ${array[*]} :

#!/bin/bash

#Array creation
black=(jon tahsan jahan tony meraz)

#printing array length to the terminal using both expressions
echo "the array elements printed using \${black[@]}: ${black[@]}"
echo               # for adding extra spaces between the outputs
echo "the array elements printed using \${black[*]}: ${black[*]}"
EXPLANATION

In the above script, the length expression ${black[@]} and ${black[*]} access the array black with 5 elements. Finally, the echo command displays all the array items in a single line to the prompt.

The output of the above code will look like this:bash print indexed array using length expressions The above snapshot states that the commands echo ${black[@]} and echo ${black[*]} both seamlessly print the 5 individual elements of the array black in a single line separated by space.

Printing an Associative Array Using Length Expression

To print the keys and values of an associative array in Bash, you can use the primary expression ${my_associative[@]}. Here’s an example:

#!/bin/bash

#declare an associative array and assign values
declare -A my_associative
my_associative["eat"]="rice"
my_associative["take"]="tea"
my_associative["drink"]="juice"

#printing the array keys
echo "keys: ${!my_associative[@]}"

#printing the array values
echo "values: ${my_associative[@]}"
EXPLANATION

Here, the expression echo keys: ${!my_associative[@]} prints the keys (take drink eat) of the associative array called my_associative. Next, the echo values: ${my_associative[@]} expression displays the values (tea juice rice) of the array in the following line.

bash print associative array using length expressionThe above Bash script successfully prints the associative array “my_associative” (both the keys and values) using length expressions  ${!my_associative[@]} and ${my_associative[@]} respectively.

2. Print an Array in Bash Using the “declare -p” Command

The declare -p command in Bash displays the current state of a variable and, regarding arrays, prints the elements of the array including its name, variable type, and index.

Below is a script to print an indexed array in Bash with index and details using the declare -p command:

#!/bin/bash

#declare an array and populate its values
declare -a cadbury=(dairy milk silk)

#use declare -p to print the array 
declare -p cadbury 
EXPLANATION

In this code snippet, after the declaration of the indexed array cadbury using the syntax declare -a cadbury=(dairy milk silk), the declare -p command prints all the elements of that array along with displaying its name, type, and indices.

The output will look like this:printing indexed bash array using declare -p command The aforementioned image states that the declare command with the -p option prints the items of the array named cadbury with its respective indices.

Print an Associative Array Using the “declare -p” Command

The below script shows an example of how to use declare -p to print an associative array:

#!/bin/bash

#declare an associative array
declare -A assoc_array

#value insertion to the array
assoc_array["fruit"]="apple"
assoc_array["vegetable"]="carrot"
assoc_array["drink"]="water"

#use declare -p to print the elements and details
declare -p assoc_array

printing bash associative array using declare -pIn the snap above, you see that the declare -p command prints the array items, indices, name, and type in a single line of the associative array named  assoc_array.

3. Print an Array in Bash Using Loops

Using loop is an effective technique to perform tasks requiring repetition such as printing the elements of an indexed or associative array in Bash. For instance, the for ((i=0; i<5; i++)) loop will do the specified task 5 times in an iterative manner.

To print the elements of an indexed array in Bash using a for loop, see the below script:

#!/bin/bash

#Declaring an indexed array and assigning it with values 
coffee=(latte americano cortado espresso)

#looping through the elements to print 
for elements in ${coffee[@]}
    do
        echo $elements
done 
EXPLANATION

First, the complete looping expression for elements in ${coffee[@]} iterates through the coffee array until it has covered the entire array length (which is 4) and prints the items into the terminal iteratively on new lines using echo $elements.

printing bash indexed array using for loopFrom the output, you may notice that the for loop prints the 4 elements of the coffee array in prints them on 4 new lines.

Printing an Associative Array Using Loop

The for loop prints a Bash associative array (both the keys and values) successfully. Here’s an example:

#!/bin/bash

#declare an associative array
declare -A my_assoc_array

#populate the array with values
my_assoc_array["fruit"]="apple"
my_assoc_array["vegetable"]="carrot"
my_assoc_array["drink"]="water"

#for loop to print the array keys and values
for key in "${!my_assoc_array[@]}"; do
  value="${my_assoc_array[$key]}"
  echo "Key: $key, Value: $value"
done
EXPLANATION

Here, the for loop first iterates through the keys of the my_assoc_array by for key in "${!my_assoc_array[@]}"; to store the corresponding element into a variable called value and finally prints the key-value pairs in the same line for each element using echo "Key: $key, Value: $value. The for loop repeats the same task until it has reached the end of the array.

bash associative array print using for loopScript output to print an associative array in Bash using for loop.

Print Array in Reverse Order

Printing an array in the reverse order means displaying the elements in the opposite order from their original sequence. For example, the output after printing the array nums_array=(1 2 3 4) in the reverse order would be 4 3 2 1. One easy way to print a Bash array in reverse is to use the for loop.

To print an indexed array in the reverse order, you can use the loop for ((i = length - 1; i >= 0; i--)) in a script like the following:

#!/bin/bash

#creating the array with 4 elements 
nums_array=(1 2 3 4)

#print the original array
echo “original array: ${nums_array[*]}”
echo #for extra space

# Get the length of the array
length=${#nums_array[@]}

echo “reversed array:”
# Iterate through the array in reverse order and print 
for ((i = length - 1; i >= 0; i--)); do
  echo "${nums_array[i]}"
done
EXPLANATION

The for loop condition for ((i = length - 1; i >= 0; i--)); states that the iteration of the nums_array starts fromthe last element and continues till the first element is located at index 0. In this repetitive manner, the for loop accesses the array in reverse and displays them to the prompt employing echo "${nums_array[i]}".

print bash indexed array in reverseThe above script prints the nums_array in its original order and then, in the reverse order (4 3 2 1) iteratively using the for loop.

NOTE: Associative arrays do not have any innate particular order whereas indexed arrays keep track of order using indices. Therefore, printing an associative array in reverse is not meaningful.

4. Print an Array in Bash Using the “printf” Command

Apart from the standard echo command, the printf command prints the elements of an array in Bash.

To print an indexed array in Bash using the printf command, see the example below:

#!/bin/bash

#create an array with 4 elements
foods=("apple" "milk" "flakes" "date")

# Using printf to print array elements on a new line
printf "%s\n" "${foods[@]}"
EXPLANATION

In the above code, the printf command prints the items of the array named foods using the expression ${foods[@]}. The \n is a newline character that tells printf to display elements with newlines. The %s accepts the elements as an argument.

print bash indexed array with printfIn the above-captured snap, you see that the printf  command prints the array elements each on a new line.

Print an Associative Array Using the “printf” Command

To print an associative array in Bash, you can use the printf command. Here’s how:

#!/bin/bash

#declare an associative array
declare -A legends

#assign values using keys
legends["virat"]="kohli"
legends["joe"]="root"
legends["kane"]="williamson"

#storing keys and values into 2 arrays named keys and values respectively
keys=("${!legends[@]}")
values=("${legends[@]}")

#printing the keys and values using the printf command
printf "Keys: %s\n" "${keys[*]}"
printf "Values: %s\n" "${values[*]}"
EXPLANATION

In the code above, the printf command takes the keys and values of the legends array and stores them into 2 arrays named keys and values using the expressions ("${!legends[@]}") and  ("${legends[@]}"). Finally, the printf command prints the keys and values in 2 separate lines because the expressions have an asterisk (*) instead of @ which treats the entire array as a single argument.

bash print associative array using printf commandThe above snap exemplifies that the printf command prints the keys and associated items of the array legends.

5. Print Specific Elements of an Array in Bash

To print specific elements out of an entire array in Bash, use array indexing and array slicing methods. The array indexing method uses the syntax echo ${array_name[idx]} to print the corresponding item by taking the index number as input in place of idx.

See below to print 4 elements out of 7 elements of an array using ${array_name[idx]}:

#!/bin/bash

#create an indexed array
num=(1 2 3 4 5 6 7)

#print all items
echo "all items: ${num[@]}"

echo  # for an extra spacing 

#print specific items 
echo "using \${num[idx]}"
echo "${num[2]}"
echo "${num[3]}"
echo "${num[4]}"
echo "${num[5]}"
EXPLANATION

Here, the command ${num[idx]} takes as input the indices (2 3 4 5) 4 times to print the 3rd to 6th elements in 4 new lines.

The code output will look like this:bash printing specific 4 items from 7 items using index Script output to print 4 elements of the array num out of 7 elements using the above script.

Using Array Slicing Methods

In the array slicing method, there are two command-centric syntaxes: echo ${array_name[@ or *]: Start} and  ${array_name[@ or *]:Start:Count}.

The 1st command ${array_name[@ or *]:Start} starts printing elements from the Start index up to the end. For instance, if the value of Start is 2, then the command prints all the values till the end from the 3rd element (index 2) till the end.

To print all the array items from index 3, you can use the command  ${array_name[@ or *]:3}. Here’s how:

#!/bin/bash

#create an indexed array
food=("apple" "banana" "cherry" "date" "grape")

#print all elements from index 3
echo ${food[@]:3}
EXPLANATION

This code snippet uses the command echo ${food[@]:3} to start printing the elements of the food array from index 3 (date) to the end of the array (grape).

print 2 specific items of a bash arrayScript output to print the 4th and 5th element (date grape) of the food array out of 5 elements using the command echo ${food[@]:3}.

In addition, the slicing expression ${array_name[@ or *]:Start:Count} slices the elements of an indexed array beginning from the index Start (0,1,2…) and extracts the number of elements specified by Count. For example, the command echo ${array_name[@ or *]:1:4} prints 4 elements starting from index 1.

To print 3 elements from an array of 7 elements starting from index 3, you can use echo ${array_name[@ or *]:3:3}. Here’s an example:

#!/bin/bash

#create an indexed array
fruits=("apple" "banana" "cherry" "date" "grape" "peach" "dragon")

#print entire array
echo ${fruits[*]}

#print 3 elements starting from index 3
echo ${fruits[@]:3:3}
EXPLANATION

Here, the expression  ${fruits[@]:3:3} begins from the 3rd index and accesses 3 elements inclusive. The echo command then prints the items to the prompt.

printing 3 elements from 7 elements of a bash arrayThe above snapshot states that the echo ${fruits[@]:3:3} command prints 3 elements (date grape peach) out of 7 elements starting from the 4th element.

NOTE: To print an associative array with specific elements, the key-based accessing method using the command echo "${assoc_array["key"]}" is recommended.

Print an Array to a File in Bash

To print the elements of an array to a file, use the output redirection operator > or >>. The > operator creates the output file if it doesn’t exist, redirects contents, and overwrites any extant content of that file during subsequent redirections. Contrarily, the >> operator appends the contents with the existing file items.

For example, to print an array to a file named output.txt using both the expressions "${your_array[@]}" > output.txt and "${your_array[@]}" >> output.txt, see the below code:

#!/bin/bash

#create an array with elements
lang_chain=("java" "mojo" "golang" "python")

# Redirect the array contents to a file (overwriting the file if it exists)
printf "%s\n" "${lang_chain[@]}" > output.txt
echo # extra spacing 
# same work (appending this time) with echo command
echo "${lang_chain[@]}" >> output.txt

#displaying contents of the file 
cat output.txt
EXPLANATION

The expression printf "%s\n" "${lang_chain[@]}" > output.txt redirects the output of printf "%s\n" "${lang_chain[@]}" (the array items) to the output.txt file. The command echo "${lang_chain[@]}" >> output.txt does the same but this time it appends the contents with no overwriting of the existing content (output of the earlier command). The cat command, syntax: cat output.txt, displays the contents for further verification.

print bash array to a fileIn the above image, you spot that the > and >> redirection operators print the array items into the file named output.txt.

Print Array Elements with Newlines in Bash

To break the array and print the items with newlines, you can use the command printf "%s\n" "${array_name[@]}". Look at the following example:

#!/bin/bash

#create an array with elements 
hello=("world" "universe" "multiverse")

# Print the array items on separate lines without a loop
printf "%s\n" "${hello[@]}"
EXPLANATION

The printf command with specifier "%s\n" prints the array hello, where the newline character \n denotes to print each element with newlines and format specifier %s, tells printf to expect array items as arguments.

bash print array with new linesScript output to print a Bash array with newlines using the printf command

Conclusion

In this extensive guide, I have mentioned 5 methods to print an array in the Bash scripting language covering both the indexed and associative arrays. Choose the method that best suits your needs. The loop is useful when you want to perform an action on each element, while directly referencing elements is convenient for printing specific elements or the entire array. Happy scripting!

People Also Ask

Can I print specific elements of an array in Bash?

Yes, you can use the array indices with the echo command like this: echo ${array[index_number]} to print the specific element. For instance, to print the 2nd element, use echo ${array[1]}.

How to print a Bash array?

To print a Bash array:

  1. Use the syntax: echo ${array_name[@]}
    OR,
  2. Use a for loop to print elements iteratively:
for elements in "${my_array[@]}"; do
  echo "$elements"
done

What is the difference between the “${array[@]}” and “${array[*]}” in Bash?

Both the expressions with the echo command print all the array items. However, “${array[@]}” treats each item as a separate entity preserving spaces while “${array[*]}” combining all the elements and treating them as a single string.

What is a Bash Array?

A Bash array is a data structure used to store information in an indexed way. The indexed array in Bash has numbered indices while the associative arrays have string indices called keys. Unlike other programming languages, Bash arrays can store elements of various data types.

How to echo array in Bash terminal?

To echo an array in a Bash terminal, you can use the echo "${array_name[@]}" syntax. This will output all elements of the array separated by spaces.

How to print the length of an array in Bash?

To print the length of an array in Bash, use the echo ${#array[@ or *]} command. It will print the number of elements presented in the array. For example, to print the length of the array num=(1 2 3):

echo ${#num[@]}

The output will be 3.

Can I print an array with new lines in Bash?

Yes, you can. To print bash arrays with new lines:

  1. Use Bash for loop to iterate over the elements to print them on separate lines like the following:
    for item in "${my_array[@]}"; do
      echo "$item"
    done
    
  2. Use the printf '%s\n' "${my_array[@]}" expression to print array items in newlines.

How do I print the key-value pairs of an associative array in a single line?

To print the key-value pairs of an associative array, use the command declare -p followed by the associative array name that you created earlier to fetch the items as well as their corresponding keys. The syntax is: declare -p associative_array_name. However, the keys are printed in random order.

Is it possible to display the indices of an indexed array in Bash?

Yes, it’s possible by simply utilizing the expression echo ${!my_array[@]} to display all the indices of an indexed array in Bash. For instance, to print the indices of the array arr=(1 2 4), use echo ${!arr[@]}. The output will be 0 1 2.

Related Articles


<< Go Back to Bash Array | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment