Split string into an array in Bash
suggest changeLet’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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents