010-160 Basic Scripting Concepts 5 — Questions and Answers
Question 1: What does `2>/dev/null` accomplish when appended to a command?
- Redirects standard output to /dev/null
- Discards standard error output (Correct answer)
- Redirects both stdout and stderr to /dev/null
- Reads input from /dev/null
Correct answer: Discards standard error output
`2>` redirects file descriptor 2 (stderr) to `/dev/null`, silently discarding error messages.
Question 2: In bash, what does the `source` command (or `.`) do when given a script path?
- Runs the script in a subshell
- Compiles the script into a binary
- Executes the script in the current shell environment (Correct answer)
- Checks the script for syntax errors only
Correct answer: Executes the script in the current shell environment
`source` (or `.`) runs the script within the current shell so its variable assignments and functions persist.
Question 3: Which character is used to redirect standard output AND standard error to the same file in bash?
- &>>
- 2>&1 combined with > (Correct answer)
- >!
- >>2
Correct answer: 2>&1 combined with >
Using `> file 2>&1` first redirects stdout to the file, then redirects stderr to wherever stdout now points.
Question 4: What is the purpose of double brackets `[[ ]]` compared to single brackets `[ ]` in bash?
- Double brackets work in POSIX sh; single brackets are bash-only
- Double brackets support regex matching and avoid word-splitting issues (Correct answer)
- Double brackets are only for arithmetic expressions
- They are completely interchangeable
Correct answer: Double brackets support regex matching and avoid word-splitting issues
`[[ ]]` is a bash keyword that adds regex matching (`=~`), avoids word-splitting, and handles empty variables more safely.
Question 5: Which special variable contains the process ID of the currently running script?
- $!
- $#
- $$ (Correct answer)
- $0
Correct answer: $$
`$$` expands to the PID of the current shell or script, often used to create unique temporary filenames.
Question 6: What does the `continue` statement do inside a bash loop?
- Exits the entire loop
- Exits the script
- Skips the rest of the current iteration and starts the next one (Correct answer)
- Restarts the loop from the beginning
Correct answer: Skips the rest of the current iteration and starts the next one
`continue` jumps back to the loop condition check, skipping the remaining commands in the current iteration.
Question 7: Which syntax correctly passes the output of `date` as an argument to `echo` using command substitution?
- echo {date}
- echo $[date]
- echo $(date) (Correct answer)
- echo %date%
Correct answer: echo $(date)
`$(command)` substitutes the command's output inline, so `echo $(date)` prints the current date.
What does `2>/dev/null` accomplish when appended to a command?