How to declare an array?

QuestionsQuestions8 SkillsProShell ArraysOct, 20 2025
0153

In Bash, you can declare an array using the following syntax:

Syntax for Declaring an Array

array_name=(element1 element2 element3 ...)

Example

Here’s an example of how to declare an array:

# Declare an array
fruits=(apple banana cherry)

# Display the array elements
echo "${fruits[@]}"  # Outputs: apple banana cherry

Alternative Syntax

You can also declare an array using the declare command:

declare -a array_name
array_name=(element1 element2 element3 ...)

Example with declare

# Declare an array using declare
declare -a vegetables
vegetables=(carrot potato tomato)

# Display the array elements
echo "${vegetables[@]}"  # Outputs: carrot potato tomato

Both methods are valid for declaring arrays in Bash.

0 Comments

no data
Be the first to share your comment!