Linux+ Linux+ Bash Scripting and Automation 2 — Questions and Answers
Question 1: Which construct is used to iterate over each line of a file in a Bash script?
- for line in $(cat file.txt)
- while IFS= read -r line < file.txt
- while IFS= read -r line; do ... done < file.txt (Correct answer)
- foreach line in file.txt
Correct answer: while IFS= read -r line; do ... done < file.txt
The while read loop with input redirection (<) is the correct and safe idiom for reading files line by line in Bash.
Question 2: What does the special variable $? represent in a Bash script?
- The process ID of the current script
- The exit status of the last executed command (Correct answer)
- The total number of arguments passed
- The name of the current script
Correct answer: The exit status of the last executed command
$? holds the exit status (return code) of the most recently executed foreground command, where 0 means success.
Question 3: Which Bash operator sends standard error to the same destination as standard output?
- 2>&1 (Correct answer)
- 1>&2
- &>2
- >>2
Correct answer: 2>&1
2>&1 redirects file descriptor 2 (stderr) to wherever file descriptor 1 (stdout) is currently pointing.
Question 4: In a Bash case statement, what symbol marks the end of each pattern block?
- ;; (Correct answer)
- break
- end
- esac
Correct answer: ;;
Each case pattern block is terminated with ;; which causes Bash to skip to the esac keyword.
Question 5: What is the purpose of the 'local' keyword inside a Bash function?
- It imports a variable from the parent shell
- It declares a variable scoped only to that function (Correct answer)
- It marks a variable as read-only
- It exports the variable to child processes
Correct answer: It declares a variable scoped only to that function
Variables declared with 'local' exist only within the function scope and do not pollute the global environment.
Question 6: Which command substitution syntax is preferred in modern Bash scripts over backticks?
- ${cmd}
- $(cmd) (Correct answer)
- `cmd`
- [[cmd]]
Correct answer: $(cmd)
$(cmd) is the preferred modern form because it nests cleanly and is more readable than backticks.
Question 7: What does 'set -e' do at the top of a Bash script?
- Enables extended globbing patterns
- Causes the script to exit immediately on any command error (Correct answer)
- Echoes every command before executing it
- Enables strict variable checking
Correct answer: Causes the script to exit immediately on any command error
set -e (errexit) makes the script terminate as soon as any command returns a non-zero exit code.
Which construct is used to iterate over each line of a file in a Bash script?