0
0
Bash Scriptingscripting~15 mins

Reading files line by line (while read) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading files line by line (while read)
📖 Scenario: You have a text file that contains a list of your favorite fruits, one fruit per line. You want to read this file line by line and print each fruit with a friendly message.
🎯 Goal: Build a bash script that reads a file called fruits.txt line by line using while read loop and prints each fruit with the message: "I like <fruit>".
📋 What You'll Learn
Create a file named fruits.txt with the exact fruits listed.
Create a variable to hold the filename.
Use a while read loop to read the file line by line.
Print each fruit with the message: "I like <fruit>".
💡 Why This Matters
🌍 Real World
Reading files line by line is common when processing logs, configuration files, or lists in scripts.
💼 Career
Many automation and system administration tasks require reading files line by line to handle data or perform actions.
Progress0 / 4 steps
1
Create the fruits.txt file
Create a file named fruits.txt with these exact lines:
Apple
Banana
Cherry
Bash Scripting
Need a hint?

Use cat with a here document to create the file.

2
Set the filename variable
Create a variable called filename and set it to fruits.txt.
Bash Scripting
Need a hint?

Use filename="fruits.txt" to assign the variable.

3
Read the file line by line
Use a while read loop with variable fruit to read each line from $filename.
Bash Scripting
Need a hint?

Use while read fruit; do ... done < "$filename" to read lines.

4
Print the output
Run the script and print the output lines exactly as:
I like Apple
I like Banana
I like Cherry
Bash Scripting
Need a hint?

Just run the script to see the output.