Bash Create an Empty Array


Bash Create an Empty Array

In Bash scripting, creating an empty array is useful for various tasks that require initializing arrays that can be populated later.


Syntax

array=()

The basic syntax involves using parentheses to initialize an empty array.


Example Bash Create an Empty Array

Let's look at some examples of how to create an empty array in Bash:

1. Initialize an Empty Array

This script initializes an empty array and prints its contents.

#!/bin/bash

array=()
echo "Array contents: ${array[@]}"

In this script, the array variable array is initialized as an empty array using (). The script then prints the contents of the array, which is empty.

Initialize an empty array in Bash

2. Initialize an Empty Array and Add Elements

This script initializes an empty array, adds elements to it, and prints its contents.

#!/bin/bash

array=()
array+=("element1")
array+=("element2")
array+=("element3")
echo "Array contents: ${array[@]}"

In this script, the array variable array is initialized as an empty array using (). Elements are added to the array using the += operator. The script then prints the contents of the array, which now includes the added elements.

Initialize an empty array and add elements in Bash

3. Initialize an Empty Array from User Input

This script initializes an empty array, prompts the user to enter elements, adds them to the array, and prints its contents.

#!/bin/bash

array=()
while true; do
    read -p "Enter an element (or 'done' to finish): " element
    if [ "$element" == "done" ]; then
        break
    fi
    array+=("$element")
done
echo "Array contents: ${array[@]}"

In this script, the array variable array is initialized as an empty array using (). The user is prompted to enter elements, which are added to the array using the += operator. When the user types 'done', the loop exits. The script then prints the contents of the array, which includes the elements entered by the user.

Initialize an empty array from user input in Bash

Conclusion

Creating an empty array in Bash is a fundamental task for initializing arrays that can be populated later in shell scripting. Understanding how to create and manipulate arrays can help you manage and organize data effectively in your scripts.