Bash Split Function: How to Split Strings in Bash
In this article
Bash does not have a built-in split function that returns an array the way JavaScript or Python do, but you can split a string in one line with the IFS variable and read -ra, or with parameter expansion for a single delimiter. The shortest working recipe is IFS=',' read -ra parts <<< "$str", which fills the array parts with each comma-separated field. Everything else in this guide builds on that pattern.
What You'll Need
- A Bash shell (version 3.2 or newer is fine; macOS ships 3.2, most Linux distributions ship 4.x or 5.x). Check with
bash --version. - A terminal or a script file where you can run commands. No extra packages are required.
- Basic familiarity with variables and arrays in Bash, since the split output is stored in an array.
Step-by-Step
- Decide what your delimiter is. A comma, a colon, a space, a tab, or a multi-character string like
::. This choice determines which method you use. Single-character delimiters work withIFS; multi-character delimiters need parameter expansion or an external tool. - Split on a single character with
IFSandread. The pattern is:IFS=',' read -ra parts <<< "$str"
HereIFSis set only for that command,-rstops backslashes from being treated as escapes,-astores the result in the array namedparts, and<<<feeds the string as standard input. This is the safest general-purpose split in Bash. - Read the results back. Loop over the array:
for p in "${parts[@]}"; do echo "[$p]"; done
The quotes around${parts[@]}are what keep fields containing spaces intact as single elements. - Split on a multi-character delimiter.
IFStreats each character as a separate delimiter, so it cannot split on::directly. Use parameter expansion instead:str="a::b::c"parts=()while [[ $str == *::* ]]; do parts+=("${str%%::*}"); str=${str#*::}; doneparts+=("$str")
This peels off everything before the first::, then everything after it, and repeats until no delimiter remains. - Split on a space or tab. Leave
IFSat its default (space, tab, newline) and runread -ra parts <<< "$str". Consecutive spaces collapse into one field, which is usually what you want for word splitting. - Split a command's output, not a variable. Pipe into
reador use a process substitution:read -ra parts <<< "$(some_command)"
If the output has multiple lines and you want one array element per line, usemapfile -t lines <<< "$(some_command)"instead. - Handle empty fields deliberately. If your input can contain
a,,c, theIFS=',' read -raform keeps the empty middle element, which is usually correct. If you want to drop empties, filter with[[ -n $p ]]in the loop. - Verify the count and each element. Print
${#parts[@]}and then each[${parts[i]}]so you can see exactly where the boundaries landed before you build logic on top of the array.
Common Mistakes
- Forgetting to quote
"${parts[@]}". Unquoted, a field containing a space gets split again and the array you carefully built falls apart. - Setting
IFSglobally. WritingIFS=','on its own line changes word splitting for the rest of the script and breaks unrelated commands. Always prefix it to the single command:IFS=',' read -ra parts <<< "$str". - Assuming
IFShandles multi-character delimiters. It does not.IFS='::'is justIFS=':'because each character is a separate separator. - Using
echoto feed the string.echo "$str" | read -ra partsrunsreadin a subshell, so the array is empty afterwards. Use<<<or process substitution instead. - Forgetting
-r. Without it, backslashes in the input are consumed and your data silently changes. - Using
cutorawkwhen a Bash split is enough. External tools spawn a process and mangle quoting; for simple in-script splits,read -rais faster and safer.
Tips
- Name your array something meaningful (
fields,parts,segments) so later code reads cleanly. - Use
declare -a parts=()before appending if you want to be explicit; it also avoids inheriting an environment variable of the same name. - For CSV with quoted commas, do not hand-roll a splitter. Use a tool that understands CSV quoting, such as
awkwith a proper field separator or a language like Python, becauseIFSwill split inside quotes. - For splitting a file path into directories,
IFS='/' read -ra segs <<< "$path"works, but remember the leading slash produces an empty first element. - If you need only the first field,
${str%%,*}is cheaper than building an array. - Test with input that contains spaces, empty fields, and trailing delimiters. Those three cases break most naive splitters.
Troubleshooting
- The array is empty after the split. You almost certainly piped into
read. Replace the pipe with<<< "$str". - Fields with spaces are broken apart. Quote the array expansion:
"${parts[@]}", not${parts[@]}. - The split ignores the second character of your delimiter. You used
IFSfor a multi-character delimiter. Switch to the parameter-expansion loop in step 4. - Backslashes disappear. Add
-rtoread. - Empty fields vanish. Check whether you are using
read -ra(keeps empties) versus a loop that filters-n(drops them). Pick the behaviour you actually want. - Script behaves differently on macOS. macOS ships Bash 3.2, which lacks some newer array features. If you rely on associative arrays or
mapfile, install a newer Bash via Homebrew or rewrite using indexed arrays only. - If that did not work, print the raw string with
printf '%q\n' "$str"to reveal hidden characters such as carriage returns from Windows line endings, then strip them withstr=${str%$'\r'}.
Frequently Asked Questions
Is there a built-in split function in Bash?
No. Bash has no function named split that returns an array. The idiomatic replacement is IFS=',' read -ra parts <<< "$str". There is a separate Unix utility called split, but it divides files into pieces, not strings.
How do I split a string on a multi-character delimiter?
Use a while loop with ${str%%delim*} and ${str#*delim} as shown in step 4, or call an external tool like awk. IFS cannot do it because it treats each character as its own separator.
Why is my array empty after echo "$str" | read -ra parts?
Because the right side of a pipe runs in a subshell, and variables set there do not survive. Use read -ra parts <<< "$str" instead.
How do I keep empty fields when splitting?
IFS=',' read -ra parts <<< "a,,c" keeps the empty middle element. If you are filtering with [[ -n $p ]], remove that check.
Can I split on a newline?
Yes. Set IFS=$'\n' for the command, or use mapfile -t lines <<< "$str", which is the standard way to read one array element per line.
Does this work in sh or dash?
Not reliably. read -a and <<< are Bash features. Run your script with #!/usr/bin/env bash and invoke it as bash script.sh if you are unsure which shell is the default.