Home Terminal Tuts 10 practical examples to master appending in Bash arrays

10 practical examples to master appending in Bash arrays

It's an invaluable resource for anyone looking to deepen their understanding of Bash scripting, providing clear demonstrations of how to effectively manipulate and expand arrays in various scenarios.

by John Horan
bash append array

Welcome back, FOSS Linux enthusiasts! I’ve spent countless hours tinkering with Bash, the default shell in many Linux distributions like Ubuntu. Today, I’m excited to dive into a topic close to my heart: appending to arrays in Bash. This might seem mundane, but once you master it, your script-writing game will level up!

Arrays in Bash might not be as sophisticated as in some high-level programming languages, but they are incredibly useful. Let’s explore how to append to arrays with 10 practical examples. I’ll be using Ubuntu for these examples, but they should work in any Bash environment.

Understanding arrays in bash

Before jumping into the examples, let’s understand what arrays are in the context of Bash. An array is a variable containing multiple values, which can be accessed by an index. Arrays in Bash are zero-indexed, meaning the first element is at index 0.

How to declare an array

To declare an array in Bash, you can simply do:

my_array=(element1 element2 element3)

Alright, enough theory. Let’s get our hands dirty with some examples!

Bash append to array explained with 10 examples

1. Appending a single element

In this example, we start with an array my_array containing three elements: ‘apple’, ‘banana’, and ‘cherry’. By using +=("date"), we append the string ‘date’ to the array. The += operator is a convenient way to add an element to the end of an array.

my_array=(apple banana cherry)
my_array+=("date")
echo${my_array[@]}

Output:

apple banana cherry date

This is the most straightforward method to append an element.

2. Appending multiple elements

Here, we have an initial array with ‘apple’ and ‘banana’. By using +=(cherry date), we append both ‘cherry’ and ‘date’ simultaneously. This showcases how += can be used to append multiple elements in one go, which is a great time-saver.

my_array=(apple banana)
my_array+=(cherry date)
echo${my_array[@]}

Output:

apple banana cherry date

Here, we append multiple elements at once. Very handy!

3. Appending elements from another array

In this scenario, we demonstrate how to append all elements from one array (array_two) to another (array_one). This is done by expanding array_two inside the parentheses. The += operator appends each element of array_two to array_one.

array_one=(apple banana)
array_two=(cherry date)
array_one+=(${array_two[@]})
echo${array_one[@]}

Output:

apple banana cherry date

Combining arrays is as simple as it gets.

4. Appending elements using a loop

This example is particularly useful when you need to append elements conditionally or in a more controlled manner. We iterate over a list of elements (‘cherry’ and ‘date’) using a for loop and append each one to the fruits array. This method provides more control over what gets appended and when.

fruits=(apple banana)
for fruit in cherry date; do
    fruits+=("$fruit")
done
echo${fruits[@]}

Output:

apple banana cherry date

A loop offers more control over what gets appended.

5. Appending elements with user input

Here, we introduce interactivity. We start with an array animals and then use read to take a new animal name as input from the user. This input is then appended to the animals array. This method is useful when the data to append is not known in advance and must be provided by the user.

animals=(cat dog)
read -p "Enter a new animal: " new_animal
animals+=("$new_animal")
echo${animals[@]}

Run this script, and it will prompt you to enter a new animal.

6. Append using indirect reference

This is a more advanced technique where we use an indirect reference (array_name) to append a new element to the array. The eval command is used to evaluate the command that appends new_number to the my_numbers array. This approach is useful when the name of the array is dynamic or not known until runtime.

array_name='my_numbers'
my_numbers=(1 2 3)
read -p "Enter a new number: " new_number
eval $array_name+=("$new_number")
echo${my_numbers[@]}

This is a bit advanced, using eval for dynamic array names.

7. Appending elements from a file

In this example, we read lines from a file (my_file.txt) and append each line to the lines array. This is done within a while loop that reads the file line by line. This method is particularly useful for processing text files.

lines=()
while IFS= read -r line; do
    lines+=("$line")
done < my_file.txt
echo${lines[@]}

Here, we read from a file and append each line to an array.

8. Appending elements using command output

Here, we append the output of a command (ls in this case) to an array. This is achieved by using a while loop that reads the output of ls line by line and appends each line (filename in this case) to the files array. This technique is handy when you need to work with the output of a command.

files=()
while IFS= read -r file; do
    files+=("$file")
done < <(ls)
echo${files[@]}

Note: While ls works, it’s better to use globbing for file manipulation.

9. Append with array expansion

This example demonstrates another method of appending elements using array expansion. We create a new array by expanding the original (nums) and then adding new elements. This method can be particularly useful when merging arrays or adding multiple elements in a more explicit manner.

nums=(1 2)
nums=("${nums[@]}" 3 4)
echo${nums[@]}

Output:

1 2 3 4

A different way, using array expansion.

10. Conditional append

Finally, we have a conditional append. We append ‘4’ to nums only if the length of nums is less than 5. This showcases how to append elements based on a condition, offering a high level of control over the array.

nums=(1 2 3)
if [[ ${#nums[@]} -lt 5 ]]; then
    nums+=("4")
fi
echo${nums[@]}

Output:

1 2 3 4

Appending based on a condition, great for control.

Frequently Asked Questions about Bash Arrays

1. How do I create an empty array in Bash?

A: To create an empty array, you can use either my_array=() or declare -a my_array.

2. How can I add elements to an array at specific positions?

A: You can add elements at specific positions using the syntax my_array[index]=value. For example, my_array[3]="apple" adds “apple” at the 4th position (since arrays are zero-indexed).

3. Can Bash arrays hold different data types?

A: Bash does not distinguish between different data types in the way that strongly typed languages do. An array in Bash can hold numbers, strings, or a mix of both.

4. How do I remove an element from a Bash array?

A: To remove an element, use unset. For example, unset my_array[2] removes the element at index 2.

5. How can I concatenate two arrays in Bash?

A: You can concatenate arrays by using array expansion: array3=("${array1[@]}" "${array2[@]}").

6. How do I find the length of an array?

A: Use ${#array[@]} to get the number of elements in an array. For example, echo ${#my_array[@]} prints the length of my_array.

7. Can I create multidimensional arrays in Bash?

A: Bash does not support multidimensional arrays natively. However, you can simulate them using clever indexing schemes or by using arrays of strings.

8. How do I iterate over an array?

A: Use a for loop: for i in "${array[@]}"; do echo $i; done.

9. How can I append to an array in a script taking input from a user?

A: Use read to take input from a user and then append it: read -p "Enter value: " value; my_array+=("$value").

10. Are Bash arrays zero-indexed or one-indexed?

A: Bash arrays are zero-indexed, meaning the first element is at index 0.

Conclusion

Arrays in Bash, while simple, are incredibly powerful. Whether you’re writing scripts for automation, data processing, or just for fun, knowing how to effectively manipulate arrays will make your life easier. Personally, I find the ability to append dynamically, especially from user input or files, incredibly useful in my scripting adventures.

The best way to learn is by doing. So, open up your terminal and start experimenting with these examples. Happy scripting!

PS: If you have any specific scenarios or questions about Bash arrays, feel free to drop a comment. I love geeking out on this stuff!

You may also like

Leave a Comment

fl_logo_v3_footer

ENHANCE YOUR LINUX EXPERIENCE.



FOSS Linux is a leading resource for Linux enthusiasts and professionals alike. With a focus on providing the best Linux tutorials, open-source apps, news, and reviews written by team of expert authors. FOSS Linux is the go-to source for all things Linux.

Whether you’re a beginner or an experienced user, FOSS Linux has something for everyone.

Follow Us

Subscribe

©2016-2023 FOSS LINUX

A PART OF VIBRANT LEAF MEDIA COMPANY.

ALL RIGHTS RESERVED.

“Linux” is the registered trademark by Linus Torvalds in the U.S. and other countries.