Bash Script to Split String by Delimiter
IFS='delimiter' and read -ra array, for example: IFS=',' read -ra parts <<< "$string" splits $string by commas into the array parts.Examples
How to Think About It
Algorithm
Code
#!/bin/bash string="apple,banana,cherry" IFS=',' read -ra parts <<< "$string" for part in "${parts[@]}"; do echo "$part" done
Dry Run
Let's trace splitting 'apple,banana,cherry' by ',' through the code
Set string
string = "apple,banana,cherry"
Set IFS and read into array
IFS=',' read -ra parts <<< "$string" results in parts = ["apple", "banana", "cherry"]
Print each element
Outputs each element on a new line: apple, banana, cherry
| Iteration | Array Element |
|---|---|
| 1 | apple |
| 2 | banana |
| 3 | cherry |
Why This Works
Step 1: Set IFS to delimiter
The IFS variable tells Bash where to split the string, so setting IFS=',' means split at commas.
Step 2: Read string into array
Using read -ra array reads the input string into an array, splitting it by the IFS delimiter.
Step 3: Access array elements
Each part of the string becomes an element in the array, which you can loop over or access by index.
Alternative Approaches
#!/bin/bash string="apple,banana,cherry" delimiter=',' while [[ $string ]]; do part=${string%%$delimiter*} echo "$part" string=${string#*$delimiter} [[ $string == $part ]] && break done
#!/bin/bash string="apple,banana,cherry" echo "$string" | cut -d',' -f1
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string requires scanning each character once, so time grows linearly with string length.
Space Complexity
An array stores each split part, so space grows with the number of parts created.
Which Approach is Fastest?
Using IFS with read -ra is efficient and simple; alternatives like loops or external commands are slower or more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| IFS and read -ra | O(n) | O(n) | Simple, efficient splitting into array |
| Parameter expansion loop | O(n) | O(1) | Manual control, no arrays, more complex |
| cut command | O(n) | O(1) | Extracting single fields, not full splitting |
IFS locally before reading to avoid affecting other parts of your script.IFS causes the string not to split as expected, returning the whole string as one element.