Bash & Shell Scripting (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
How do you safely read a file line-by-line in Bash?
junior LevelCode Examplebash-shellBasic
In Simple Words:
Never use for line in $(cat file.txt) (it splits words by spaces and strips empty lines!).
- The Universal Safe Pattern:
bash
while IFS= read -r line || [[ -n "$line" ]]; do
echo "Processing: $line"
done < "data.txt"
IFS=: Clears internal field separator to preserve leading/trailing whitespace.-r: Disables backslash escaping.|| [[ -n "$line" ]]: Ensures the final line is processed even if it lacks a trailing newline.