Linux+ Linux+ Bash Scripting and Automation 3 — Questions and Answers
Question 1: Which Bash test expression correctly checks if a file exists AND is readable?
- [ -e file && -r file ]
- [[ -e file -a -r file ]]
- [[ -f file || -r file ]]
- [[ -e file && -r file ]] (Correct answer)
Correct answer: [[ -e file && -r file ]]
[[ -e file && -r file ]] uses the modern double-bracket syntax with && to combine both existence and readability tests.
Question 2: What does the trap command accomplish in a Bash script?
- Captures output from a subprocess
- Registers a handler to execute when a signal or event occurs (Correct answer)
- Prevents a script from being interrupted
- Locks a file descriptor during write operations
Correct answer: Registers a handler to execute when a signal or event occurs
trap associates a command or function with a signal (like INT or EXIT) so cleanup code runs on termination.
Question 3: In Bash arithmetic, which syntax evaluates an integer expression and returns its value?
- $[expr]
- $(( expr )) (Correct answer)
- {{ expr }}
- $(expr)
Correct answer: $(( expr ))
$(( expr )) is the POSIX-compliant arithmetic expansion syntax for integer math in Bash.
Question 4: Which getopts usage correctly parses a script option '-f' that requires an argument?
- getopts 'f' opt
- getopts 'f:' opt (Correct answer)
- getopts '-f:' opt
- getopts 'f;' opt
Correct answer: getopts 'f:' opt
A colon after the option letter in the optstring tells getopts that the option requires an argument, stored in $OPTARG.
Question 5: What is the output of: echo ${#myvar} when myvar='hello'?
- hello
- 5 (Correct answer)
- $myvar
- 0
Correct answer: 5
${#varname} is the Bash parameter expansion that returns the length of the variable's string value.
Question 6: Which command creates a named pipe (FIFO) in Linux?
- mkpipe
- mknod -p
- mkfifo (Correct answer)
- pipe
Correct answer: mkfifo
mkfifo creates a named pipe (FIFO special file) that allows inter-process communication via the filesystem.
Question 7: A script uses 'exec 3< inputfile'. What does file descriptor 3 now represent?
- An output pipe to inputfile
- A read-only file descriptor open on inputfile (Correct answer)
- A copy of stderr redirected to inputfile
- An append-mode descriptor for inputfile
Correct answer: A read-only file descriptor open on inputfile
exec 3< inputfile opens inputfile for reading on file descriptor 3, allowing the script to read from it independently of stdin.
Which Bash test expression correctly checks if a file exists AND is readable?