Hint: bash -x shows commands with + before output [OK]
Common Mistakes:
Ignoring the debug lines starting with +
Choosing output without debug info
Confusing else branch output
4. This script is intended to check if a file exists and print a message, but it fails. What is the error?
#!/bin/bash
filename="myfile.txt"
if [ -f $filename ]
then
echo "File exists"
else
echo "File missing"
fi
medium
A. The if statement syntax is incorrect; should use double brackets [[ ]]
B. Missing quotes around $filename can cause errors if filename has spaces
C. The script needs to use -e instead of -f to check file existence
D. The echo commands must be inside curly braces { }
Solution
Step 1: Identify variable usage in test condition
The variable $filename is unquoted, which can cause errors if it contains spaces.
Step 2: Understand quoting importance in bash tests
Quoting variables prevents word splitting and errors in test expressions.
Final Answer:
Missing quotes around $filename can cause errors if filename has spaces -> Option B
Quick Check:
Quote variables in tests = Missing quotes around $filename can cause errors if filename has spaces [OK]
Hint: Always quote variables in test conditions [OK]
Common Mistakes:
Thinking [[ ]] is required instead of [ ]
Confusing -f and -e options
Believing echo needs braces
5. You want to test a script that processes user input and exits with code 0 on success or 1 on failure. Which strategy best helps automate testing this behavior?
hard
A. Write test cases that run the script with different inputs and check the exit code using $?
B. Only run the script manually and watch the output on screen
C. Use echo statements inside the script without checking exit codes
D. Rename the script file to .test and run it without arguments
Solution
Step 1: Understand exit codes in bash scripts
Scripts use exit codes to signal success (0) or failure (non-zero).
Step 2: Automate testing by running script with inputs and checking $?
Running script with inputs and verifying $? confirms correct behavior automatically.
Final Answer:
Write test cases that run the script with different inputs and check the exit code using $? -> Option A
Quick Check:
Test exit codes with $? = Write test cases that run the script with different inputs and check the exit code using $? [OK]
Hint: Check $? after running script to verify success/failure [OK]
Common Mistakes:
Relying only on manual output checks
Ignoring exit codes in tests
Assuming renaming files triggers tests
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.