Bird
0
0

Which command correctly reads a file named data.txt line by line in bash?

easy🧠 Conceptual Q2 of 15
Bash Scripting - File Operations in Scripts
Which command correctly reads a file named data.txt line by line in bash?
Aread line < data.txt; echo $line
Bfor line in data.txt; do echo $line; done
Ccat data.txt | for line in; do echo $line; done
Dwhile read line; do echo "$line"; done < data.txt
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct syntax for reading lines

    The while read line; do ... done < file pattern reads each line properly.
  2. Step 2: Check other options for errors

    The read line < data.txt; echo $line reads only one line. The for line in data.txt; do echo $line; done iterates over the filename as a single item. The cat data.txt | for line in; do echo $line; done has a syntax error due to incomplete for loop syntax.
  3. Final Answer:

    while read line; do echo "$line"; done < data.txt -> Option D
  4. Quick Check:

    Correct syntax = D [OK]
Quick Trick: Use while read with input redirection to read lines [OK]
Common Mistakes:
MISTAKES
  • Using for loop incorrectly
  • Reading only one line
  • Misusing pipes with loops

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes