Bird
0
0

You want to write a recursive Bash function list_files that prints all files in a directory and its subdirectories. Which approach correctly handles recursion and avoids infinite loops?

hard🚀 Application Q15 of 15
Bash Scripting - Functions
You want to write a recursive Bash function list_files that prints all files in a directory and its subdirectories. Which approach correctly handles recursion and avoids infinite loops?
ACheck if the argument is a directory; if yes, list files and call list_files on each subdirectory; else print the file name
BCall list_files on the directory without checking type, then print the directory name
CUse a loop to list files only in the current directory without recursion
DCall list_files on all files and directories without base case
Step-by-Step Solution
Solution:
  1. Step 1: Understand recursive directory traversal

    To list files recursively, check if the argument is a directory; if so, process contents recursively.
  2. Step 2: Avoid infinite loops by checking file type

    Only recurse into directories; print file names directly to avoid infinite recursion.
  3. Final Answer:

    Check if the argument is a directory; if yes, list files and call list_files on each subdirectory; else print the file name -> Option A
  4. Quick Check:

    Directory check + recursive call = correct recursion [OK]
Quick Trick: Always check if input is directory before recursive call [OK]
Common Mistakes:
MISTAKES
  • Recursing without checking if input is directory
  • Missing base case causing infinite recursion
  • Not printing files when input is a file

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes