Linux Shell Scripting 5 — Questions and Answers
Question 1: What does `set -u` do in a bash script?
- Unsets all variables
- Treats unset variables as an error when they are expanded (Correct answer)
- Enables Unicode support
- Updates the PATH variable
Correct answer: Treats unset variables as an error when they are expanded
`set -u` causes the script to exit with an error if an unset variable is referenced, catching typos early.
Question 2: How do you append a line to a file inside a shell script without overwriting it?
- echo 'line' > file
- echo 'line' >> file (Correct answer)
- echo 'line' | file
- echo 'line' >| file
Correct answer: echo 'line' >> file
`>>` appends to a file; `>` truncates and overwrites.
Question 3: What is the output of `echo $((3 ** 2))` in bash?
- 32
- 9 (Correct answer)
- 6
- Error
Correct answer: 9
`**` is the exponentiation operator in bash arithmetic; `3 ** 2` equals 9.
Question 4: Which syntax correctly declares an indexed array in bash?
- arr = (one two three)
- arr=(one two three) (Correct answer)
- array arr = [one, two, three]
- declare arr = {one two three}
Correct answer: arr=(one two three)
In bash, `arr=(value1 value2 ...)` initializes an indexed array with space-separated values.
Question 5: What does `${arr[@]}` expand to when `arr` is a bash array?
- The number of elements in the array
- All array elements as separate words (Correct answer)
- The first element only
- The last element only
Correct answer: All array elements as separate words
`${arr[@]}` expands each element as a separate word, preserving elements with spaces when quoted.
Question 6: Which `getopts` call correctly processes a flag `-v` and an option `-o` that takes an argument?
- getopts "v:o" opt
- getopts "vo:" opt (Correct answer)
- getopts "-v -o:" opt
- getopts "v|o:" opt
Correct answer: getopts "vo:" opt
In `getopts`, a colon after a letter means it takes an argument; `vo:` means `-v` is a flag and `-o` requires a value.
Question 7: What is the purpose of `exec > logfile.txt` inside a bash script?
- Replaces the current process with logfile.txt
- Redirects all subsequent stdout of the script to logfile.txt (Correct answer)
- Executes logfile.txt as a script
- Pipes stdout to logfile.txt temporarily
Correct answer: Redirects all subsequent stdout of the script to logfile.txt
`exec > file` permanently redirects the shell's stdout to a file for all subsequent commands in that script.
What does `set -u` do in a bash script?