Bash Create an Array with Elements


Bash Create an Array with Elements

In Bash scripting, creating an array with elements is useful for various tasks that require initializing arrays with predefined values.


Syntax

array=(element1 element2 element3)

The basic syntax involves using parentheses to initialize an array with elements separated by spaces.


Example Bash Create an Array with Elements

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

1. Create an Array with Predefined Elements

This script initializes an array with predefined elements and prints its contents.

#!/bin/bash

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

In this script, the array variable array is initialized with the elements 'element1', 'element2', and 'element3'. The script then prints the contents of the array.

Create an array with predefined elements in Bash

2. Create an Array with Elements from User Input

This script prompts the user to enter elements, adds them to an 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.

Create an array with elements from user input in Bash

Conclusion

Creating an array with elements in Bash is a fundamental task for initializing arrays with predefined values in shell scripting. Understanding how to create and manipulate arrays can help you manage and organize data effectively in your scripts.