LCA Shell Scripting & Automation 3 — Questions and Answers
Question 1: Which operator is used for arithmetic expansion in bash?
- $(( )) (Correct answer)
- $[ ]
- expr
- let
Correct answer: $(( ))
The `$(( ))` syntax performs arithmetic expansion and is the preferred POSIX-compatible method.
Question 2: How do you redirect both stdout and stderr to the same file in bash?
- command &> file (Correct answer)
- command > file 1>&2
- command 2> file 1>&2
- command | file
Correct answer: command &> file
`&>` is bash shorthand for redirecting both stdout (fd 1) and stderr (fd 2) to the same destination.
Question 3: What does `command -v ls` return when `ls` is found in PATH?
- The full path or alias of ls (Correct answer)
- The version of ls
- The output of ls
- Nothing; it only sets $?
Correct answer: The full path or alias of ls
`command -v` prints the resolved path or alias for a command, making it useful for checking if a command exists.
Question 4: In a bash script, which syntax correctly passes an array as individual arguments to a function?
- func "${arr[@]}" (Correct answer)
- func "${arr[*]}"
- func $arr
- func $(arr)
Correct answer: func "${arr[@]}"
`"${arr[@]}"` expands each array element as a separate quoted word, preserving elements with spaces.
Question 5: What is the purpose of `exec 3>&1` in a bash script?
- Saves the current stdout to file descriptor 3 (Correct answer)
- Redirects fd 3 to /dev/null
- Creates a new pipe
- Closes file descriptor 1
Correct answer: Saves the current stdout to file descriptor 3
`exec 3>&1` duplicates stdout to fd 3, allowing you to save and later restore the original stdout.
Question 6: Which construct in bash is used to perform pattern matching in a case statement?
- case $VAR in pattern) ... ;; esac (Correct answer)
- switch $VAR { pattern: ... }
- match $VAR with pattern -> ...
- if $VAR == pattern; then ...
Correct answer: case $VAR in pattern) ... ;; esac
The `case ... esac` construct uses glob patterns to match values and execute corresponding code blocks.
Question 7: What does the `local` keyword do inside a bash function?
- Declares a variable scoped to the function (Correct answer)
- Makes a variable read-only
- Exports a variable to child processes
- Unsets a global variable
Correct answer: Declares a variable scoped to the function
`local` creates a variable whose scope is limited to the enclosing function and its children.
Which operator is used for arithmetic expansion in bash?