Bird
0
0

You want to read a file line by line and skip empty lines. Which script snippet correctly does this?

hard🚀 Application Q15 of 15
Bash Scripting - File Operations in Scripts
You want to read a file line by line and skip empty lines. Which script snippet correctly does this?
Awhile read line; do echo "$line"; done < file.txt | grep '^$'
Bwhile IFS= read -r line; do if [[ -n $line ]]; then echo "$line"; fi; done < file.txt
Ccat file.txt | while read line; do echo "$line"; done
Dwhile IFS= read -r line; do echo "$line"; done < file.txt
Step-by-Step Solution
Solution:
  1. Step 1: Understand skipping empty lines

    We need to check if the line is not empty using [[ -n $line ]].
  2. Step 2: Confirm reading and condition

    while IFS= read -r line; do if [[ -n $line ]]; then echo "$line"; fi; done < file.txt reads lines safely and prints only non-empty lines inside the loop.
  3. Final Answer:

    while IFS= read -r line; do if [[ -n $line ]]; then echo "$line"; fi; done < file.txt -> Option B
  4. Quick Check:

    Condition inside loop filters empty lines = A [OK]
Quick Trick: Use if [[ -n $line ]] inside loop to skip empty lines [OK]
Common Mistakes:
MISTAKES
  • Using external grep after loop (may lose variable scope)
  • Not checking for empty lines inside the loop
  • Using unnecessary cat command

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes