LCA Shell Scripting & Automation 5 — Questions and Answers
Question 1: Which bash option enables strict mode by catching unset variable references?
- set -u (Correct answer)
- set -e
- set -x
- set -o pipefail
Correct answer: set -u
`set -u` (or `set -o nounset`) causes the shell to treat unset variables as an error and exit.
Question 2: What does `set -o pipefail` change about pipeline exit status?
- The pipeline returns the exit status of the last failed command, not just the last command (Correct answer)
- All commands in the pipeline run in parallel
- The pipeline stops at the first failure
- Errors in the pipeline are ignored
Correct answer: The pipeline returns the exit status of the last failed command, not just the last command
Without `pipefail`, a pipeline's exit status is the last command's status; with it, any failure in the pipeline propagates.
Question 3: In bash, what is a here-document used for?
- Providing multi-line input to a command inline in the script (Correct answer)
- Defining a function
- Importing another script
- Creating a temporary file automatically
Correct answer: Providing multi-line input to a command inline in the script
A here-document (`<< DELIMITER ... DELIMITER`) feeds multiple lines of text directly as stdin to a command without needing a separate file.
Question 4: Which command schedules a one-time job to run at 3:00 AM tonight on a Linux system?
- echo 'command' | at 03:00 (Correct answer)
- cron '0 3 * * *' command
- schedule command --time 03:00
- batch --at 03:00 command
Correct answer: echo 'command' | at 03:00
The `at` command schedules one-time tasks; you pipe the command to `at` with a time argument.
Question 5: What is the correct way to source a file named `config.sh` in the current shell?
- . config.sh (Correct answer)
- exec config.sh
- run config.sh
- include config.sh
Correct answer: . config.sh
The dot (`.`) command or `source` built-in reads and executes commands from the file in the current shell environment.
Question 6: Which tool is best suited for parsing and transforming structured text using field separators in a shell pipeline?
- awk (Correct answer)
- grep
- find
- sort
Correct answer: awk
awk is designed for field-based text processing and supports custom field separators with the -F option.
Question 7: What does `nohup script.sh &` accomplish?
- Runs the script in the background, immune to hangup signals when the terminal closes (Correct answer)
- Runs the script with no output
- Runs the script as root
- Schedules the script to run later
Correct answer: Runs the script in the background, immune to hangup signals when the terminal closes
`nohup` ignores the SIGHUP signal, and `&` backgrounds the process so it continues after logout.
Which bash option enables strict mode by catching unset variable references?