Bash – Split string by comma

To split a string by comma character into an array of values in Bash scripting, you can set IFS (Internal Field Separator) variable with comma, and then use read command with options ra to read the string to an array.

Once the values are into an array, we can access them using a For Loop.

Once we are done with the split operation, set IFS with its default value.

Example

In the following script, we take a string in str which contains values separated by comma. We split this string into values, and then print each of them to output.

example.sh

#!/bin/bash
 
str="apple,banana,cherry,mango"

# hyphen (-) is set as delimiter
IFS=','

# str is read into an array as tokens separated by IFS
read -ra values <<< "$str"

#echo each of the value to output
for value in "${values[@]}"; do
    echo "$value"
done

# reset IFS to default value
IFS=' '

Output

sh-3.2# ./example.sh 
apple
banana
cherry
mango

References

Bash For Loop

ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to split a string by comma separator.