Bash by Example: Read File
Reading file contents using various Unix utilities including cat for entire files, head for first lines, tail for last lines and real-time monitoring, understanding line-by-line processing with while read loops for large files, implementing efficient file parsing strategies, and choosing the right tool based on file size and processing needs.
Code
#!/bin/bash
# Create a sample file
printf "Line 1\nLine 2\nLine 3\nLine 4\nLine 5" > sample.txt
echo "--- Whole File (cat) ---"
cat sample.txt
echo -e "\n--- First 2 Lines (head) ---"
head -n 2 sample.txt
echo -e "\n--- Last 2 Lines (tail) ---"
tail -n 2 sample.txt
echo -e "\n--- Line by Line Loop ---"
line_num=1
while IFS= read -r line; do
echo "$line_num: $line"
((line_num++))
done < sample.txt
rm sample.txtExplanation
To display the entire contents of a file, cat (concatenate) is the standard tool. For large files, less or more are preferred for interactive viewing, but cat is used for scripts.
To read only parts of a file, head (start of file) and tail (end of file) are extremely efficient. tail -f is famous for monitoring log files in real-time.
When you need to process a file line-by-line in Bash, use a while read loop with input redirection. This is slower than text processing tools like awk or sed, but allows you to use shell logic for each line.
Code Breakdown
cat dumps the whole file to stdout. Simple and effective for small files.while read loop pattern. IFS= ensures leading whitespace is preserved. -r prevents backslash interpretation.< sample.txt happens at the end of the loop block. This feeds the file into the loop.
