Languages
[Edit]
EN

Bash - create array

3 points
Created by:
Teilsa
1255

This article, we would like to show you how to create an array in Bash.

There are several ways to create an array in Bash:

  1. by using array syntax:
    #!/bin/bash
    
    array=(1 two 'third value' "fourth value")
    or:
    #!/bin/bash
    
    array=(
        1
        two
        'three'
        "four"
    )
  2. by using declare command:
    #!/bin/bash
    
    declare -a array=(1 two 'third value' "fourth value")
  3. by assigning single values:
    #!/bin/bash
    
    array[0]=1
    array[1]=two
    array[2]='third value'
    array[3]="fourth value"
    Note: when we try to assign values to non-existing array the array is created automatically.

 

Usage example

#!/bin/bash

array=(1 two 'third value' "fourth value")

for i in "${array[@]}"
do
	echo "$i"
done

Output:

1
two
third value
fourth value

 

See also

  1. Bash - iterate through array values
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Bash

Bash - create array
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join