skip to content
Alvin Lucillo

Split a string into an array in bash

/ 1 min read

💻 Tech

In bash, you can split a string into an array using the read command. For example, if you have a string of comma separated values, you can split them into an array like so:

IFS=', ' read -r -a EXCLUDED <<< $JOBS

IFS is the internal field separator. It’s used to split the string into an array. The -r flag prevents backslash escapes from being interpreted. The -a flag tells read to split the string into an array. The EXCLUDED variable is the name of the array. The JOBS variable is the string to split.

For example, if JOBS="foo, bar, baz", then EXCLUDED will be an array with the values foo, bar, and baz.