How to split a string in Bash
Split a string into an array in Bash using IFS and read -ra, or with a custom delimiter. Covers CSV lines, paths, and multi-character separators.
Tldr
The safest way to split a string on a delimiter is `IFS="," read -ra parts <<< "$str"`, which fills the array `parts` correctly even with special characters. For simple whitespace splitting, unquoted `$str` word-splits automatically, but that is fragile — prefer the explicit `read -ra` form.
Intro
Bash has no built-in split() function, so splitting relies on IFS (Internal Field Separator) combined with word-splitting or the read builtin. This guide shows the reliable patterns and the common footguns.
Steps
Name
Split on a single-character delimiter with read
Text
Setting IFS just for the read command (not globally) is the safest pattern — it does not leak the field separator change to the rest of the script.
Name
Loop over the resulting parts
Text
Quote the array expansion as usual to avoid re-splitting elements that themselves contain spaces.
Name
Split on whitespace (the default IFS)
Text
If the delimiter is any run of spaces/tabs/newlines, an unquoted expansion inside (( )) parentheses splits automatically — this is effectively how `read -a` behaves with default IFS.
Name
Split on a multi-character delimiter
Text
IFS only supports single characters as separators. For a multi-character delimiter, use parameter expansion in a loop, or substitute the delimiter with a single-character placeholder first.
Name
Split a path on / without a loop
Text
For paths, Bash parameter expansion often replaces the need for a full split: use ${var%/*} for the directory and ${var##*/} for the basename.
Faq
Q
Why does IFS=',' followed by a bare loop misbehave?
A
Setting IFS globally changes word-splitting for the rest of the script, which can silently break unrelated commands. Scope it to a single command with `IFS=',' read -ra parts <<< "$str"` instead of `IFS=','` on its own line.
Q
Can IFS be more than one character?
A
IFS can hold multiple characters, but each one is treated as an independent single-character delimiter (e.g. IFS=", " splits on comma OR space), not as a multi-character sequence.
Q
What is the fastest way to split CSV with commas inside quoted fields?
A
IFS-based splitting cannot respect quoting rules. For real CSV with quoted commas, use a proper CSV tool like `csvkit`, `mlr` (Miller), or `awk -F, ...` with care, rather than plain Bash splitting.