Different Ways to Read a File in Bash Script
In this article
You can read a file in a bash script using several methods, including the cat command, a while read loop, the mapfile builtin, and command substitution. The best choice depends on whether you need to process the file line by line, store its contents in an array, or handle large files efficiently.
Why the Method Matters
Bash scripts often need to consume configuration files, logs, CSV exports, or lists of items. The way you read a file affects memory usage, speed, and how you handle special characters, blank lines, and trailing newlines. A naive approach like cat file dumps everything to stdout, which is fine for display but not for programmatic processing. For robust scripting, you want a method that preserves data integrity and gives you control over each line.
1. Using cat and Command Substitution
The simplest way to read a file into a variable is:
content=$(cat file.txt)
echo "$content"
This reads the entire file into a single string, stripping trailing newlines. It works well for small files where you need the whole content at once. However, command substitution removes trailing newlines and can be slow for very large files because it creates a subshell. Also, if the file contains null bytes, bash will truncate the content at the first null.
2. The while read Loop (Most Common)
For line-by-line processing, the standard pattern is:
while IFS= read -r line; do
echo "$line"
done < file.txt
Here, -r prevents backslash escapes from being interpreted, and IFS= preserves leading/trailing whitespace. Without these, you might lose spaces or have backslashes mangled. This loop reads one line at a time, so it is memory-efficient for large files. A common mistake is to put the redirection inside the loop, which would re-open the file each iteration—always place < file at the end of the done statement.
3. Using mapfile (Bash 4+)
If you need the entire file in an array, mapfile (also known as readarray) is the cleanest way:
mapfile -t lines < file.txt
for line in "${lines[@]}"; do
echo "$line"
done
The -t option strips trailing newlines from each element. This is much faster than a while loop for large files because it reads the whole file in one go, but it uses more memory. It also handles files without a trailing newline correctly, which is a common edge case.
4. Using sed or awk for Specific Lines
Sometimes you only need a range of lines or to extract fields. sed -n '10,20p' file prints lines 10 to 20. awk '{print $1}' file prints the first field of each line. These are not general-purpose file readers, but they are ideal for extracting data without writing a full loop. For example, to read the second line of a file:
second_line=$(sed -n '2p' file.txt)
This approach is concise and fast for targeted reads.
5. Process Substitution and read from a Command
You can read from a command's output as if it were a file using process substitution:
while IFS= read -r line; do
echo "$line"
done < <(command_that_outputs_text)
This is useful when you want to process the output of a command (like ls or find) without creating a temporary file. The syntax <(...) creates a file descriptor that the loop reads from. It behaves like a regular file, so you can use any of the reading methods with it.
Common Pitfalls and How to Avoid Them
- Trailing newline removal: Command substitution strips trailing newlines. If you need to preserve them, use
mapfileor a loop. - Whitespace loss: Without
IFS=in awhile readloop, leading and trailing spaces are removed. Always setIFS=unless you specifically want that behavior. - Backslash interpretation: Using
readwithout-rwill treat backslashes as escape characters, corrupting paths likeC:\Users\name. - Empty lines: In a
while readloop, an empty line is read as an empty variable, which is fine. But if you usecatand then iterate withfor, empty lines are skipped because word splitting ignores them. - Missing trailing newline: Some files don't end with a newline. A
while readloop will still process the last line, butcatmight not show a prompt after it.mapfilehandles this gracefully.
How to Choose the Right Method
Consider the following factors:
- File size: For files larger than a few MB, avoid reading the entire file into memory unless necessary. Use
while read. - Need for an array: If you need random access to lines, use
mapfile. - Simple display: Use
cat. - Field extraction: Use
awk. - Line range: Use
sed. - Binary files: Bash is not suitable for reading binary files; use tools like
xxdorodinstead.
Frequently Asked Questions
Why does my while read loop lose the last line?
If the file doesn't end with a newline, the last line may not be processed because the loop condition fails when read returns non-zero at EOF. To fix this, you can add || [[ -n $line ]] to the loop condition, but this can cause issues if the last line is empty. A simpler solution is to use mapfile which handles this automatically.
What is the difference between read and cat for files?
cat outputs the entire file to stdout, which you can capture with command substitution. read reads one line at a time from a file descriptor. cat is simpler but less flexible for processing individual lines. read is the building block for loops.
Can I read a file without a subshell?
Yes, using mapfile or a while read loop with redirection does not create a subshell. Command substitution like $(cat file) always runs in a subshell, which means any variable changes inside are lost. Loops and mapfile run in the current shell, so you can modify variables.
How do I read a file into an array in bash?
Use mapfile -t array < file. This creates an array where each element is a line without the trailing newline. You can then access elements with ${array[0]}, ${array[1]}, etc., and iterate with for line in "${array[@]}".
What is the fastest way to read a large file in bash?
For very large files, mapfile is faster than a while read loop because it reads in bulk. However, it uses more memory. If memory is a concern, use while read. For extremely large files (GBs), consider using awk or sed which are optimized C programs and will be much faster than any bash loop.
Why do I need IFS= in a while read loop?
By default, read uses the Internal Field Separator (IFS) to split the line into fields. If IFS contains spaces or tabs, leading and trailing whitespace is trimmed. Setting IFS= (empty) prevents this trimming, so you get the exact line content. This is crucial for preserving indentation or spaces in data.