Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Bash Split Function: How to Split Strings in Bash

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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 with IFS; multi-character delimiters need parameter expansion or an external tool.
  2. Split on a single character with IFS and read. The pattern is:
    IFS=',' read -ra parts <<< "$str"
    Here IFS is set only for that command, -r stops backslashes from being treated as escapes, -a stores the result in the array named parts, and <<< feeds the string as standard input. This is the safest general-purpose split in Bash.
  3. 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.
  4. Split on a multi-character delimiter. IFS treats 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#*::}; done
    parts+=("$str")
    This peels off everything before the first ::, then everything after it, and repeats until no delimiter remains.
  5. Split on a space or tab. Leave IFS at its default (space, tab, newline) and run read -ra parts <<< "$str". Consecutive spaces collapse into one field, which is usually what you want for word splitting.
  6. Split a command's output, not a variable. Pipe into read or use a process substitution:
    read -ra parts <<< "$(some_command)"
    If the output has multiple lines and you want one array element per line, use mapfile -t lines <<< "$(some_command)" instead.
  7. Handle empty fields deliberately. If your input can contain a,,c, the IFS=',' read -ra form keeps the empty middle element, which is usually correct. If you want to drop empties, filter with [[ -n $p ]] in the loop.
  8. 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 IFS globally. Writing IFS=',' 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 IFS handles multi-character delimiters. It does not. IFS='::' is just IFS=':' because each character is a separate separator.
  • Using echo to feed the string. echo "$str" | read -ra parts runs read in 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 cut or awk when a Bash split is enough. External tools spawn a process and mangle quoting; for simple in-script splits, read -ra is 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 awk with a proper field separator or a language like Python, because IFS will 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 IFS for a multi-character delimiter. Switch to the parameter-expansion loop in step 4.
  • Backslashes disappear. Add -r to read.
  • 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 with str=${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.