FUNDAMENTALS A Complete Guide for Beginners
You can use the following 5 methods to print an array in Bash:
- To print the entire array:
${your_array[@ or *]}
- To print the array index, value, and type:
declare -p <your_array>
- To print the array iteratively:
for item in ${your_array[@]} do echo $item done
- To print the array in new lines:
printf "%s\n" "${array_name[@]}"
- 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[*]}"
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: 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[@]}"
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.
${!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
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: 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
In 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
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 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
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.
Script 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
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]}"
.
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[@]}"
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.
In 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[*]}"
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.
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]}"
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: 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}
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).
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}
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.
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
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 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[@]}"
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.
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:
- Use the syntax:
echo ${array_name[@]}
OR, - 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:
- 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
- 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
- Declare Array in Bash [Create, Initialize]
- How to Read into Bash Array [3 Methods]
- Index Array in Bash [Explained]
- Bash Associative Arrays [Explained]
- Bash Array of Arrays [Explained]
- Elements of Bash Array
- How to Get the Length of an Array in Bash?[Complete Guide]
- Array Operations in Bash
<< Go Back to Bash Array | Bash Scripting Tutorial