Bird
0
0

You want to write a shell script that reads a filename from the user and prints "File exists" if it exists. Which snippet correctly implements this?

hard🚀 Application Q9 of 15
Bash Scripting - Basics
You want to write a shell script that reads a filename from the user and prints "File exists" if it exists. Which snippet correctly implements this?
A#!/bin/bash read -p "Enter filename: " file if [ -e "$file" ]; then echo "File exists" fi
B#!/bin/bash read file if [ -f file ]; then echo "File exists" fi
C#!/bin/bash read -p "Enter filename: " file if [ -d $file ]; then echo "File exists" fi
D#!/bin/bash read -p "Enter filename: " file if [ -e file ]; then echo "File exists" fi
Step-by-Step Solution
Solution:
  1. Step 1: Use read with prompt and variable

    read -p "Enter filename: " file correctly reads input into variable file.
  2. Step 2: Test file existence with -e and quote variable

    Use [ -e "$file" ] to check if file exists, quoting variable to handle spaces.
  3. Final Answer:

    #!/bin/bash read -p "Enter filename: " file if [ -e "$file" ]; then echo "File exists" fi -> Option A
  4. Quick Check:

    Proper input and file test syntax = #!/bin/bash read -p "Enter filename: " file if [ -e "$file" ]; then echo "File exists" fi [OK]
Quick Trick: Quote variables in tests to handle spaces [OK]
Common Mistakes:
MISTAKES
  • Not quoting variables
  • Using -d to check files instead of directories
  • Missing prompt in read

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes