CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingMedium
A system administrator is writing a Bash script that needs to create a directory `/var/log/myapp` if it does not already exist. They also want to ensure that the script exits immediately if the directory creation fails due to permissions or any other error. Which Bash command or construct would best achieve this?
- Amkdir /var/log/myapp || exit 1
- Bif ! [ -d /var/log/myapp ]; then mkdir /var/log/myapp; fi
- Cmkdir -p /var/log/myapp && echo 'Directory created'
- Dset -e mkdir /var/log/myapp
Show answer & explanationAnswer & explanation
Correct answer: D. set -e mkdir /var/log/myapp
The `set -e` command (or `set -o errexit`) ensures that the script exits immediately if any command fails (returns a non-zero exit status). When `mkdir` fails (e.g., due to permissions), `set -e` will cause the script to terminate, fulfilling the requirement.
Why the other options are wrong
- A. While `|| exit 1` makes the script exit on `mkdir` failure, `mkdir` without `-p` will fail if the directory already exists, which is often not the desired behavior when checking for existence. It also doesn't create parent directories.
- B. This checks if the directory exists and creates it if not. It's robust for existence but doesn't inherently cause the script to exit on `mkdir` failure without additional error handling.
- C. `mkdir -p` creates parent directories and does not fail if the directory already exists, which is good. However, the `&&` operator will only execute the `echo` command if `mkdir` succeeds, it won't exit the script on failure.
Bash `set -e` (errexit)
A Bash shell option that causes the script to exit immediately if a command exits with a non-zero status.
- Also known as `set -o errexit`.
- Ensures script robustness by preventing execution after a critical command failure.
- Does not affect commands in `if`, `while`, `until` conditions, or commands in `&&` or `||` lists.
- Useful for preventing unexpected behavior from partial command execution.
Memory trick: Handle errors in Bash: exit on failure, or check every step.