Bird
0
0

You want to create a script that accepts a filename as argument and prints "File exists" if it exists. Which script snippet is correct?

hard🚀 Application Q9 of 15
Bash Scripting - Basics
You want to create a script that accepts a filename as argument and prints "File exists" if it exists. Which script snippet is correct?
A#!/bin/bash if [ -f "$1" ]; then echo "File exists" fi
B#!/bin/bash if [ $1 ]; then echo "File exists" fi
C#!/bin/bash if [ -d "$1" ]; then echo "File exists" fi
D#!/bin/bash if [ "$1" == "file" ]; then echo "File exists" fi
Step-by-Step Solution
Solution:
  1. Step 1: Understand file existence test in bash

    Use -f to check if a regular file exists at the path given by $1.
  2. Step 2: Identify correct conditional syntax

    #!/bin/bash if [ -f "$1" ]; then echo "File exists" fi correctly uses [ -f "$1" ] to test file existence and prints message.
  3. Final Answer:

    #!/bin/bash\nif [ -f "$1" ]; then\necho "File exists"\nfi -> Option A
  4. Quick Check:

    Check file existence with -f and $1 argument = #!/bin/bash if [ -f "$1" ]; then echo "File exists" fi [OK]
Quick Trick: Use [ -f "$1" ] to test if file exists in bash [OK]
Common Mistakes:
MISTAKES
  • Using -d which checks directories
  • Not quoting $1 causing errors
  • Comparing $1 to string 'file' incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes