Bird
0
0

What is the output of this script if the current directory contains files: file1.txt, file2.log, and a directory named docs?

medium📝 Command Output Q4 of 15
Bash Scripting - Loops
What is the output of this script if the current directory contains files: file1.txt, file2.log, and a directory named docs?
for item in *; do if [ -d "$item" ]; then echo "Dir: $item"; else echo "File: $item"; fi; done
ADir: docs Dir: file1.txt Dir: file2.log
BFile: docs File: file1.txt File: file2.log
CDir: docs File: file1.txt File: file2.log
DFile: file1.txt File: file2.log
Step-by-Step Solution
Solution:
  1. Step 1: Understand the loop and condition

    The loop iterates over all items in the current directory. For each item, it checks if it is a directory with '[ -d "$item" ]'.
  2. Step 2: Determine output for each item

    'docs' is a directory, so it prints 'Dir: docs'. 'file1.txt' and 'file2.log' are files, so it prints 'File: file1.txt' and 'File: file2.log'.
  3. Final Answer:

    Dir: docs File: file1.txt File: file2.log -> Option C
  4. Quick Check:

    Directory check prints Dir, else File = A [OK]
Quick Trick: Use '[ -d ]' to check if item is directory [OK]
Common Mistakes:
MISTAKES
  • Confusing files as directories
  • Ignoring the if condition
  • Assuming only files are listed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes