0
0
Bash Scriptingscripting~20 mins

Writing to files (echo, printf) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Writer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the content of the file after running this script?
Consider the following bash script that writes to a file named output.txt. What will be the content of output.txt after running it?
Bash Scripting
echo "Hello World" > output.txt
printf "Line1\nLine2\n" >> output.txt
AHello World\nLine1\nLine2
BHello World\nLine1 Line2
CHello World
DLine1\nLine2
Attempts:
2 left
💡 Hint
Remember that > overwrites the file and >> appends to it.
💻 Command Output
intermediate
2:00remaining
What does this command write to the file?
What will be the exact content of data.txt after running this command?
Bash Scripting
printf "%s\n" "apple" "banana" "cherry" > data.txt
Aapple\nbanana\ncherry
Bapple\nbanana\ncherry\n
Capple\nbanana cherry
Dapple banana cherry
Attempts:
2 left
💡 Hint
Each %s\n prints the string followed by a newline.
📝 Syntax
advanced
2:00remaining
Which option correctly appends a line with a variable to a file?
You want to append the text "User: alice" to a file named log.txt, where the username is stored in a variable user. Which command is correct?
Bash Scripting
user=alice
Aprintf 'User: $user\n' >> log.txt
Becho 'User: $user' >> log.txt
Cprintf "User: $user\n" > log.txt
Decho "User: $user" >> log.txt
Attempts:
2 left
💡 Hint
Think about how single and double quotes handle variables.
🔧 Debug
advanced
2:00remaining
Why does this script not write the expected content to the file?
This script is intended to write "Count: 5" to count.txt. Why does it fail?
Bash Scripting
count=5
echo 'Count: $count' > count.txt
ABecause single quotes prevent variable expansion, so $count is written literally.
BBecause echo does not support variables.
CBecause the file count.txt is read-only.
DBecause the > operator only works with printf.
Attempts:
2 left
💡 Hint
Check how quotes affect variables inside echo.
🚀 Application
expert
3:00remaining
How to write a multi-line formatted report to a file using printf?
You want to create a report file report.txt with the following content exactly (including newlines):

Report Summary:
- Total: 10
- Passed: 8
- Failed: 2
End of Report

Which command correctly writes this using a single printf command?
Aecho -e "Report Summary:\n- Total: 10\n- Passed: 8\n- Failed: 2\nEnd of Report" > report.txt
Bprintf 'Report Summary:\n- Total: 10\n- Passed: 8\n- Failed: 2\nEnd of Report\n' > report.txt
Cprintf "Report Summary:\n- Total: %d\n- Passed: %d\n- Failed: %d\nEnd of Report\n" 10 8 2 > report.txt
D
printf "Report Summary:
- Total: 10
- Passed: 8
- Failed: 2
End of Report" > report.txt
Attempts:
2 left
💡 Hint
Use printf format specifiers and escape sequences carefully.