How to split a string into an array in Bash
Codemia Knowledge Hub ·
Use IFS=',' read -r -a array <<< "$string": set IFS to the delimiter for that one command and let read -a fill the array. Bash word splitting depends on quoting and IFS, so the right variant depends on whether you need to preserve spaces, empty fields or special characters.
Split on a delimiter with IFS and read -a
This keeps the delimiter local to the read command instead of changing IFS for the whole script.
Split a space-separated string
read -a also works when the separator is whitespace, but Bash treats whitespace specially during word splitting, so multiple spaces may collapse:
That is fine for simple space-separated data, but not when empty fields or repeated whitespace must be preserved exactly.
Simple CSV-like records
IFS=',' read -a is acceptable for CSV-like data only when the format is simple and unquoted:
It is not a CSV parser. If fields can contain quoted commas, embedded spaces or escaping, use a proper parser.
Split into characters
Bash has no built-in operator that splits every character, but a loop does it cleanly:
This is much more predictable than forcing character splitting through shell word expansion.
Avoid changing IFS globally
Older scripts often save and restore IFS manually. That works, but scoping the value to one read command is cleaner:
It avoids subtle bugs where later code unexpectedly uses the modified delimiter rules. Also quote the input variable ("$line") so it does not trigger unwanted shell expansion.
When Bash is the wrong tool
Bash is good at simple tokenization, not general parsing. For CSV, JSON or nested delimiters, array splitting gets fragile quickly, and awk, python, jq or another parsing tool is safer. Rule of thumb: if the delimiter logic is simple, Bash can handle it; if quoting rules matter, use a parser built for structured text.
Related reading
- How to split data on balanced training set and test set on sklearn
- How to store a hash table in a file?
- How to store arrays in MySQL?
- How to sum all the values in a dictionary?
- How to switch position of two items in a Python list?
- How to take the first N items from a generator or list?
- How to tell if an array is a permutation in On?
- How to test if a dictionary contains a specific key?
Course lessons on this

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.