0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Split String in Bash: Simple Syntax and Examples

In bash, you can split a string by setting the IFS (Internal Field Separator) to the delimiter and using the read command or array assignment. This lets you break a string into parts easily for further processing.
📐

Syntax

To split a string in bash, you typically set the IFS variable to the delimiter character, then use read or array assignment to separate the string into parts.

  • IFS=delimiter read -ra array_name <<< "$string": splits string into array elements.
  • IFS=delimiter; array=($string): splits string into array using word splitting.
bash
IFS=',' read -ra parts <<< "apple,banana,cherry"
echo "${parts[0]}"
echo "${parts[1]}"
echo "${parts[2]}"
Output
apple banana cherry
💻

Example

This example shows how to split a comma-separated string into an array and print each element on its own line.

bash
string="red,green,blue"
IFS=',' read -ra colors <<< "$string"
for color in "${colors[@]}"; do
  echo "$color"
done
Output
red green blue
⚠️

Common Pitfalls

Common mistakes include not resetting IFS after splitting, which can affect other commands, or using the wrong delimiter. Also, splitting without quotes can cause unexpected word splitting.

bash
string="one two three"
# Wrong: splits on spaces but may cause issues
array=($string)
echo "${array[0]}"  # one

# Right: explicitly set IFS and use read
IFS=' ' read -ra array <<< "$string"
echo "${array[0]}"  # one
Output
one one
📊

Quick Reference

  • IFS: Internal Field Separator, set to delimiter.
  • read -ra: reads input into an array.
  • array=(): assigns split words to array.
  • Always quote variables to avoid unwanted splitting.

Key Takeaways

Set IFS to your delimiter before splitting the string.
Use read -ra to split string into an array safely.
Always quote your variables to prevent unwanted word splitting.
Reset IFS if you change it to avoid side effects.
Splitting strings in bash is simple with IFS and read commands.