Bash Read File Examples: Read Whole File and Line by Line
Bash Read File – To read a file in Bash Scripting, you may use cat command or use “<” to open file and attach it to a standard input device handle of some application. In this Bash Tutorial, we shall present you with syntax and examples to read a file.
In Bash, the right method depends on what you want to do with the file. If you want to store the complete file content in a variable, command substitution works. If you want to process records safely, a while read loop is usually a better choice. This tutorial covers both approaches with examples.
Example : Bash Read File using – cat fileName
Syntax
value=`cat FileName`
Sample File
Learn Bash Scripting.
Welcome to TutorialKart!
Learn Bash with examples.
Bash Script File
#!/bin/sh
value=`cat sampleFile.txt`
echo "$value"
$ ./read-file-example
Learn Bash Scripting.
Welcome to TutorialKart!
Learn Bash with examples.
The above example stores the output of cat sampleFile.txt in the variable value. The double quotes in echo "$value" are important because they preserve line breaks when printing the variable.
Example : Bash Read File using – $(<fileName)
Syntax
value=$(<FileName)
Bash Shell
~/workspace/bash/file$ value=$(<sample.txt)
~/workspace/bash/file$ echo $value
Learn Bash Scripting.
Welcome to TutorialKart!
Learn Bash with examples.
The $(<fileName) form is a Bash shortcut for reading the content of a file through input redirection. It avoids starting a separate cat process, but it is Bash-specific. Use it in scripts that run with Bash, for example with #!/usr/bin/env bash.
Bash Read Whole File into a Variable with Modern Command Substitution
Backticks work in shell scripts, but the modern command substitution syntax $(...) is easier to read and nest. The following Bash script reads the whole file content into a variable and prints it.
file_content=$(cat file_name)
Example Bash script:
#!/usr/bin/env bash
file_content=$(cat sampleFile.txt)
printf '%s\n' "$file_content"
Using printf is preferred in scripts because it behaves more predictably than echo, especially when file content begins with hyphens or contains backslash sequences.
Bash Read File Line by Line Using while read
When you need to process each line separately, use a while loop with read. This is useful for configuration files, lists of names, log files, CSV-like text files, and any file where each line should be handled one at a time.
while IFS= read -r line; do
# process each line here
done < file_name
Example:
#!/usr/bin/env bash
while IFS= read -r line; do
printf 'Line: %s\n' "$line"
done < sampleFile.txt
Line: Learn Bash Scripting.
Line: Welcome to TutorialKart!
Line: Learn Bash with examples.
In this command, IFS= prevents Bash from trimming leading and trailing whitespace. The -r option prevents backslashes from being treated as escape characters. These two details make the loop safer for reading plain text exactly as it appears in the file.
Bash Read File Line by Line and Handle the Last Line Without Newline
Some text files do not end with a final newline character. In that case, a simple while read loop may skip the last line in some situations. The following form handles the last line even when the file does not end with a newline.
#!/usr/bin/env bash
while IFS= read -r line || [ -n "$line" ]; do
printf 'Line: %s\n' "$line"
done < sampleFile.txt
The condition || [ -n "$line" ] checks whether line still has content after read reaches the end of the file. This is a common defensive pattern when scripts must process every line reliably.
Bash Read File Only If It Exists and Is Readable
Before reading a file in a script, it is often useful to check whether the file exists and whether the current user can read it. This avoids confusing error messages later in the script.
#!/usr/bin/env bash
file_path="sampleFile.txt"
if [ ! -f "$file_path" ]; then
printf 'File not found: %s\n' "$file_path" >&2
exit 1
fi
if [ ! -r "$file_path" ]; then
printf 'File is not readable: %s\n' "$file_path" >&2
exit 1
fi
while IFS= read -r line; do
printf '%s\n' "$line"
done < "$file_path"
The -f test checks for a regular file. The -r test checks whether the file is readable. Quoting "$file_path" allows the script to work correctly even when the file path contains spaces.
Bash Read File Methods: When to Use cat, Redirection, and while read
| Requirement | Recommended Bash method | Reason |
|---|---|---|
| Display a file on screen | cat fileName | Simple and clear for printing file content. |
| Store whole file content in a variable | value=$(cat fileName) or value=$(<fileName) | Useful when the file is small and the content must be reused as one string. |
| Process each line separately | while IFS= read -r line | Safer for records, lists, and files where whitespace should be preserved. |
| Read a file path stored in a variable | done < "$file_path" | Quoting protects paths with spaces and special characters. |
| Handle missing or unreadable files | [ -f "$file" ] and [ -r "$file" ] | Makes the script fail with a clear message. |
Common Mistakes When Reading Files in Bash
- Using
for line in $(cat file)to read lines: this splits the file by whitespace, not by lines, so spaces inside a line are not preserved. - Forgetting quotes around variables: use
"$line"and"$file_path"to avoid word splitting and pathname expansion. - Using
read linewithout-r: without-r, backslashes may be interpreted instead of being read literally. - Reading large files into one variable: for large files, prefer a line-by-line loop instead of storing the entire file in memory.
- Assuming
$(<file)works in every shell: it is a Bash shortcut, so use Bash when writing scripts with this syntax.
FAQs on Bash Read File Examples
How do I read a file line by line in Bash?
Use while IFS= read -r line; do ... done < fileName. This reads one line at a time, preserves spaces, and reads backslashes literally.
How do I read the whole file into a Bash variable?
You can use value=$(cat fileName) or the Bash-specific shortcut value=$(<fileName). This is suitable for small files where the complete content is needed as one value.
Why is while read better than for line in $(cat file)?
for line in $(cat file) splits content by whitespace, so a line with spaces becomes multiple items. while IFS= read -r line reads actual lines and preserves the text more accurately.
What does IFS= read -r mean in Bash file reading?
IFS= prevents trimming of leading and trailing whitespace. -r prevents backslashes from being treated as escape characters. Together, they help read each line as-is.
How do I check whether a file can be read in Bash?
Use [ -f "$file" ] to check that the path is a regular file and [ -r "$file" ] to check that it is readable before opening it in the script.
Bash Read File Tutorial Editorial QA Checklist
- Confirm that examples distinguish Bash-specific syntax such as
$(<file)from POSIX shell syntax. - Check that line-by-line examples use
IFS= read -rwhen preserving file content matters. - Verify that file path variables are quoted in new Bash examples.
- Ensure output examples match the sample file content exactly.
- Confirm that the tutorial warns against
for line in $(cat file)for line-based reading.
Conclusion
In this Bash Read File tutorial, we learned how to read a complete file using cat, how to use Bash input redirection with $(<fileName), and how to process a file line by line using while IFS= read -r. For small files, storing the content in a variable is convenient. For scripts that process records or large text files, reading line by line is usually the safer method.
TutorialKart.com