CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingEasy
A system administrator needs to write a Bash script that takes a single argument, which is a directory path. The script should verify if the provided path exists and is indeed a directory. If not, it should print an error message and exit with a non-zero status. Which of the following conditional statements correctly performs this check?
- Aif [ -f $1 ]; then echo "Error: $1 is a file."; exit 1; fi
- Bif [ ! -d $1 ]; then echo "Error: $1 is not a directory."; exit 1; fi
- Cif [ -e $1 ]; then echo "Error: $1 exists."; exit 1; fi
- Dif [ -d $1 ]; then echo "Success: $1 is a directory."; exit 0; fi
Show answer & explanationAnswer & explanation
Correct answer: B. if [ ! -d $1 ]; then echo "Error: $1 is not a directory."; exit 1; fi
The `-d` test operator checks if a file exists and is a directory. The `!` negates the result, so `! -d $1` checks if the argument `$1` is NOT a directory. If this condition is true, the script prints an error and exits with a non-zero status, as required.
Why the other options are wrong
- A. This checks if the path is a file, which is not the primary requirement to check for a directory.
- C. This checks if the path exists, but doesn't specifically verify if it's a directory.
- D. This checks if it IS a directory and exits successfully, which is the opposite of the error handling required.
Bash Conditional Test `-d`
The Bash `-d` test operator is used within conditional expressions (e.g., `[ ]` or `[[ ]]`) to determine if a given path refers to an existing directory.
- `-d path` returns true if `path` exists and is a directory.
- Often used with `!` for negation, e.g., `! -d path` (not a directory).
- Part of file test operators for scripting.
Memory trick: Directory's door: is it there, or is it not?