CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingEasy
A system administrator is writing a Bash script to automate the backup of critical configuration files. The script needs to ensure that it only proceeds if the backup directory exists and is writable. Which of the following conditional statements effectively checks if the directory `/var/backups/config` exists and is writable by the script's user?
- Aif [ -d /var/backups/config ] && [ -w /var/backups/config ]; then
- Bif test -f /var/backups/config -a -x /var/backups/config; then
- Cif [ -s /var/backups/config ] -and [ -r /var/backups/config ]; then
- Dif [[ -e /var/backups/config || -p /var/backups/config ]]; then
Show answer & explanationAnswer & explanation
Correct answer: A. if [ -d /var/backups/config ] && [ -w /var/backups/config ]; then
Option A correctly uses `[ -d directory ]` to check if the path is a directory and `[ -w directory ]` to check if it is writable. The `&&` operator ensures both conditions must be true.
Why the other options are wrong
- B. This checks for a regular file (`-f`) and executability (`-x`), not a directory and writability. The `-a` operator is an older AND.
- C. This checks for a non-empty file (`-s`) and readability (`-r`), and `-and` is not a valid operator within `[`.
- D. This uses `||` (OR) and checks for existence (`-e`) or named pipe (`-p`), which is incorrect for the requirements.
Bash Conditional Tests
Bash conditional tests are used within `if` statements or `[[ ]]` constructs to evaluate expressions and determine script flow. They check file attributes, string comparisons, or arithmetic operations.
- `-d file` checks if file exists and is a directory.
- `-w file` checks if file exists and is writable.
- `&&` performs a logical AND operation between conditions.
Memory trick: Directory Writable And Go!