Split string into an array in Bash

suggest change

Let’s say we have a String parameter and we want to split it by comma

my_param="foo,bar,bash"

To split this string by comma we can use;

IFS=',' read -r -a array <<< "$my_param"

Here, IFS is a special variable called Internal field separator which defines the character or characters used to separate a pattern into tokens for some operations.

To access an individual element:

echo "${array[0]}"

To iterate over the elements:

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

To get both the index and the value:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents