0
0
Bash Scriptingscripting~20 mins

Looping over files and directories in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output of this script when run in a directory with files a.txt, b.txt, and c.log?
Consider this bash script:
for file in *.txt; do echo "$file"; done
What will it print?
Bash Scripting
for file in *.txt; do echo "$file"; done
A*.txt
B
a.txt
b.txt
C
a.txt
b.txt
c.log
D
a.txt
b.txt
*.txt
Attempts:
2 left
💡 Hint
The wildcard *.txt matches only files ending with .txt.
💻 Command Output
intermediate
2:00remaining
What does this script output if the directory contains subdirectories dir1 and dir2?
Given this script:
for entry in *; do if [ -d "$entry" ]; then echo "$entry"; fi; done
What will it print?
Bash Scripting
for entry in *; do if [ -d "$entry" ]; then echo "$entry"; fi; done
A
dir1
dir2
B
dir1
dir2
file.txt
C*.txt
Dfile.txt
Attempts:
2 left
💡 Hint
The test -d checks if the entry is a directory.
📝 Syntax
advanced
2:00remaining
Which option correctly loops over all .log files and prints their names?
Choose the correct bash loop syntax to print all .log files in the current directory.
Afor file in *.log; do echo $file; done
Bfor file in *.log { echo $file; }
Cfor (file in *.log); do echo $file; done
Dforeach file in *.log; do echo $file; done
Attempts:
2 left
💡 Hint
Bash uses 'for var in list; do ... done' syntax.
🚀 Application
advanced
3:00remaining
How to count the number of files (not directories) in the current directory using a loop?
You want to count files only (exclude directories). Which script correctly does this?
A
count=0
for item in *; do count=$((count+1)); done
echo $count
B
count=0
for item in *; do if [ -d "$item" ]; then count=$((count+1)); fi; done
echo $count
C
count=0
for item in *; do if [ -f "$item" ]; then count=$((count+1)); fi; done
echo $count
D
count=0
for item in *; do if [ -e "$item" ]; then count=$((count+1)); fi; done
echo $count
Attempts:
2 left
💡 Hint
Use -f to test if an entry is a regular file.
🔧 Debug
expert
3:00remaining
Why does this script fail to print filenames with spaces correctly?
Script:
for file in $(ls *.txt); do echo "$file"; done

What is the problem?
Bash Scripting
for file in $(ls *.txt); do echo "$file"; done
AIt loops over directories instead of files
BIt does not expand *.txt pattern
CIt causes a syntax error due to missing quotes
DIt splits filenames on spaces, so multi-word names break into parts
Attempts:
2 left
💡 Hint
Command substitution splits output by spaces and newlines.