0
0
Bash Scriptingscripting~5 mins

Looping over files and directories in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What command is commonly used in bash to loop over all files in a directory?
The for loop is commonly used with a wildcard pattern like for file in *; do ... done to loop over all files in the current directory.
Click to reveal answer
beginner
How do you loop over only directories in bash?
Use a pattern that matches directories, for example: for dir in */; do ... done. The trailing slash / ensures only directories are matched.
Click to reveal answer
beginner
What does the following script do?<br>
for file in *.txt; do echo "$file"; done
It loops over all files ending with .txt in the current directory and prints each filename on its own line.
Click to reveal answer
intermediate
Why should you quote variables like "$file" inside loops?
Quoting variables prevents word splitting and preserves spaces or special characters in filenames, avoiding errors during processing.
Click to reveal answer
intermediate
How can you loop over files recursively in bash?
You can use the find command with a loop, for example:<br>find . -type f -name "*.txt" -exec bash -c 'echo "$0"' {} \; or use a while read loop with find and read.
Click to reveal answer
Which pattern matches only directories in a bash for loop?
A*/
B*
C*.txt
D.*
What is the purpose of quoting variables like "$file" inside loops?
ATo prevent word splitting and handle spaces in filenames
BTo make the script run faster
CTo convert filenames to uppercase
DTo ignore hidden files
How do you loop over all .txt files in the current directory in bash?
Awhile read file; do ... done < *.txt
Bfor file in *; do if file ends with .txt; done
Cloop *.txt
Dfor file in *.txt; do ... done
Which command helps to loop over files recursively in bash?
Als -R
Bfind
Cgrep
Dcat
What does the wildcard * match in bash?
AOnly files starting with a dot
BOnly files with extensions
CAll files and directories except hidden ones
DOnly directories
Explain how to loop over all files in a directory using bash scripting.
Think about using a for loop with * and why quoting matters.
You got /4 concepts.
    Describe how to loop over directories only and why the pattern differs from looping over files.
    Directories end with a slash in patterns.
    You got /3 concepts.