LCA Shell Scripting & Automation 2 — Questions and Answers
Question 1: Which construct is used in bash to iterate over a list of files matching a glob pattern?
- for f in /etc/*.conf; do ...; done (Correct answer)
- while read f < /etc/*.conf; do ...; done
- foreach f in /etc/*.conf; do ...; done
- loop f=/etc/*.conf; do ...; done
Correct answer: for f in /etc/*.conf; do ...; done
The for loop with a glob pattern expands the pattern and iterates over each matching file.
Question 2: What does the `set -e` option do in a bash script?
- Exits the script immediately if any command returns a non-zero exit status (Correct answer)
- Enables extended globbing
- Echos each command before executing it
- Sets environment variables from a file
Correct answer: Exits the script immediately if any command returns a non-zero exit status
`set -e` causes the shell to exit immediately when a command exits with a non-zero status.
Question 3: Which command reads a line of input from the user and stores it in a variable named REPLY?
- read (Correct answer)
- input
- get
- scan
Correct answer: read
The `read` command without a variable name stores input in the default variable $REPLY.
Question 4: In a bash script, what is the value of `$?` after a command succeeds?
- 0 (Correct answer)
- 1
- -1
- 255
Correct answer: 0
A zero exit status ($?) indicates that the previous command completed successfully.
Question 5: What does `trap 'rm -f /tmp/lockfile' EXIT` accomplish in a script?
- Removes the lockfile when the script exits for any reason (Correct answer)
- Removes the lockfile only on normal exit
- Runs the command before the script starts
- Traps the EXIT signal and ignores it
Correct answer: Removes the lockfile when the script exits for any reason
The `trap ... EXIT` command registers a cleanup handler that runs whenever the script exits, including on error or signal.
Question 6: Which bash feature allows you to test if a variable is set and non-empty using `[[ -n $VAR ]]`?
- String length test (Correct answer)
- File existence test
- Arithmetic comparison
- Pattern matching
Correct answer: String length test
The `-n` flag inside `[[ ]]` tests whether the string length is non-zero, i.e., the variable is set and non-empty.
Question 7: What output does `echo ${#MYVAR}` produce if MYVAR='hello'?
- 5 (Correct answer)
- hello
- 1
- 0
Correct answer: 5
The `${#var}` parameter expansion returns the length of the string stored in the variable.
Which construct is used in bash to iterate over a list of files matching a glob pattern?