Quick Cheat Sheet: Bash String to Array
Common Scenarios and One-Liners
bash
# Space-separated string (most common)
string="apple banana orange"
read -ra arr <<< "$string"
# Comma-separated string
string="apple,banana,orange"
IFS=',' read -ra arr <<< "$string"
# Pipe-separated string
string="apple|banana|orange"
IFS='|' read -ra arr <<< "$string"
# Multiple delimiters (comma, semicolon, pipe)
string="apple,banana;orange|grape"
IFS=',;|' read -ra arr <<< "$string"
# Multiline string to array (recommended)
string=$'apple\nbanana\norange'
mapfile -t arr <<< "$string"
# Read file into array (line by line)
mapfile -t arr < file.txt
# Null-delimited input (advanced)
printf "apple\0banana\0orange" | mapfile -d '' -t arrSpace vs Delimiter vs Multiline (When to Use What)
| Input Type | Example Input | Recommended Method | Why |
|---|---|---|---|
| Space-separated | apple banana orange |
read -ra |
Fast and simple |
| Custom delimiter | apple,banana,orange |
IFS + read -ra |
Flexible delimiter control |
| Multiple delimiters | apple,banana;orange |
`IFS=',; | ' read -ra` |
| Multiline string | apple\nbanana\norange |
mapfile -t |
Safe and clean |
| File input | lines in file.txt | mapfile -t < file |
Efficient for files |
| Null-delimited input | apple\0banana\0orange |
mapfile -d '' |
Handles special chars safely |
| Unknown / unsafe input | user-generated strings | mapfile |
Avoids word splitting issues |
HINT
Use
mapfile when dealing with complex or unpredictable input. Use read -ra for quick and simple scripts. If you need to build input dynamically, see concatenate strings in Bash.
Convert String to Array in Bash (Core Methods Explained)
Using read -ra (Best for Most Cases)
bash
# Space-separated string
string="apple banana orange"
read -ra arr <<< "$string"
echo "${arr[@]}"- Splits based on whitespace (default IFS)
- Fast and commonly used
- Best for simple scripts. After splitting, you can iterate over elements using a for loop in Bash.
Using IFS with Custom Delimiters
bash
# Comma-separated string
string="apple,banana,orange"
IFS=',' read -ra arr <<< "$string"
echo "${arr[@]}"
bash
# Pipe-separated string
string="apple|banana|orange"
IFS='|' read -ra arr <<< "$string"- Use when input has a known delimiter
- Supports multiple delimiters. You can also validate values after splitting using string comparison in Bash.
Using mapfile / readarray (Multiline & Files)
bash
# Multiline string
string=$'apple\nbanana\norange'
mapfile -t arr <<< "$string"
echo "${arr[@]}"
bash
# Read from file
mapfile -t arr < file.txt- Safest method for multiline or file input
- Avoids modifying IFS
- Handles complex input reliably
Split String by Delimiter into Array (Real Scenarios)
Comma-Separated String to Array
bash
string="red,green,blue"
IFS=',' read -ra colors <<< "$string"
echo "${colors[@]}"Space-Separated String to Array
bash
string="one two three"
read -ra arr <<< "$string"
echo "${arr[@]}"Multiple Delimiters (IFS=',;|')
bash
string="apple,banana;orange|grape"
IFS=',;|' read -ra arr <<< "$string"
echo "${arr[@]}"- Useful when input format is inconsistent
- Works for CSV-like or mixed delimiter data. For pattern-based extraction, see print next word after pattern match.
Convert Multiline String to Array in Bash
Using mapfile -t (Recommended)
bash
# Multiline string
string=$'apple\nbanana\norange'
mapfile -t arr <<< "$string"
echo "${arr[@]}"- Each line becomes one array element
- Removes trailing newline with
-t - Best choice for structured multiline input. Combine this with a while loop in Bash for conditional processing.
Using read with while loop (Alternative)
bash
string=$'apple\nbanana\norange'
arr=()
while IFS= read -r line; do
arr+=("$line")
done <<< "$string"
echo "${arr[@]}"- More control over processing each line
- Useful if you need to filter or modify values while reading
- Slightly slower than
mapfile
Advanced: mapfile -d Delimiter (Null / Custom Delimiter)
mapfile -d '' (Null Delimited Input)
bash
# Null-delimited input (used in safe scripting)
printf "apple\0banana\0orange" | mapfile -d '' -t arr
echo "${arr[@]}"- Uses null (
\0) as delimiter instead of newline - Safest way to handle filenames and special characters
- Common in combination with commands like
find -print0, similar to examples in remove duplicate files using shell script.
When to Use mapfile -d vs IFS
| Scenario | Use This Method | Reason |
|---|---|---|
| Simple delimiter (comma etc.) | IFS + read -ra |
Faster and simpler |
| Multiline input | mapfile -t |
Clean and reliable |
| Null-delimited input | mapfile -d '' |
Handles special characters safely |
| Complex or unknown input | mapfile |
Avoids word splitting issues |
HINT
Prefer
mapfile when input may contain spaces, special characters, or unpredictable formatting.
Common Errors and Edge Cases
Why arr=($string) Breaks (Word Splitting Issue)
bash
string="apple banana orange"
arr=($string)
echo "${arr[@]}"- Performs word splitting + glob expansion
- Breaks if values contain spaces
- Can expand wildcards like
*unexpectedly - Unsafe for user input
bash
# Example problem
string="apple 'red banana' orange"
arr=($string)
# Output becomes incorrect due to splittingAvoid this method unless you fully control the input
Handling Spaces Inside Values
bash
# Problem case
string="apple 'red banana' orange"
# Safe approach using delimiter
string="apple|red banana|orange"
IFS='|' read -ra arr <<< "$string"
echo "${arr[@]}"- Use a delimiter that does not appear inside values
- Avoid whitespace splitting when values contain spaces. You can further filter values using remove elements from array in Bash.
Special Characters and Safe Input Handling
bash
# Unsafe (can break with special chars)
string="file name with spaces.txt"
arr=($string)
# Safe approach using mapfile
printf "%s\n" "file name with spaces.txt" | mapfile -t arr
echo "${arr[@]}"
bash
# Best practice for filenames (null-delimited)
find . -type f -print0 | mapfile -d '' -t files- Use
mapfilefor robust handling - Prefer null-delimited input for file operations. This is useful when parsing logs or files as shown in count occurrences of word in file.refer null-delimited input for file operations
- Avoid relying on default word splitting
Performance & Best Practice
read vs mapfile (Which is Faster?)
| Method | Speed | Best Use Case |
|---|---|---|
read -ra |
Faster | Simple strings |
IFS + read |
Fast | Custom delimiter |
mapfile |
Slightly slower | Multiline / files |
readis lightweight and faster for small inputmapfileis optimized for bulk input (files, large data)- Performance difference is negligible for most scripts. For handling multiple tasks efficiently, see run shell scripts in parallel.Performance difference is negligible for most scripts
Avoiding IFS Side Effects in Scripts
bash
# Bad practice (modifies global IFS)
IFS=','
# Good practice (limit scope)
IFS=',' read -ra arr <<< "$string"
bash
# Restore IFS if modified
OLD_IFS="$IFS"
IFS=',' read -ra arr <<< "$string"
IFS="$OLD_IFS"- Changing
IFSglobally can break other parts of script - Always limit scope or restore it after use
HINT
Use
mapfile when you want to avoid dealing with IFS entirely
Frequently Asked Questions
1. How do I convert a string to an array in Bash?
Use read -ra arr <<< "$string" to split a string into an array based on whitespace in Bash.2. How to split a string by delimiter into an array in Bash?
Use IFS with read, for example IFS=',' read -ra arr <<< "$string" to split by comma or any custom delimiter.3. How to convert multiline string to array in Bash?
Use mapfile -t arr <<< "$string" to safely store each line as an array element.4. What is mapfile -d in Bash?
mapfile -d allows you to split input using a custom delimiter such as null character, useful for handling filenames and special characters.Summary
- Use
read -rafor space-separated strings (fast and simple) - Use
IFS + readfor custom delimiters like comma, pipe, or semicolon - Use
mapfile -tfor multiline strings or file input - Use
mapfile -d ''for null-delimited data (safe for filenames and special characters) - Avoid
arr=($string)as it can break due to word splitting and glob expansion
👉 Rule of thumb:
- Simple input →
read -ra - Structured / multiline / unknown input →
mapfile
Related Bash Articles
- Learn how to concatenate strings in Bash before splitting input
- Iterate arrays efficiently using for loop in Bash
- Filter array elements with remove elements from array in Bash
- Parse text patterns using print next word after pattern match

