LCA Shell Scripting & Automation 4 — Questions and Answers
Question 1: Which cron field position specifies the day of the week?
- Fifth field (0-7, where 0 and 7 = Sunday) (Correct answer)
- Fourth field (0-6)
- Sixth field (1-7)
- Third field (0-6)
Correct answer: Fifth field (0-7, where 0 and 7 = Sunday)
In a standard crontab, the five fields are minute, hour, day-of-month, month, day-of-week; the fifth field is day-of-week where both 0 and 7 represent Sunday.
Question 2: What does `awk '{print $NF}' file` print?
- The last field of each line (Correct answer)
- The first field of each line
- The number of fields on each line
- The line count
Correct answer: The last field of each line
`NF` is the built-in awk variable for the number of fields, so `$NF` refers to the last field.
Question 3: Which sed command deletes lines 3 through 7 from a file's output?
- sed '3,7d' file (Correct answer)
- sed '3-7d' file
- sed -d '3:7' file
- sed '3..7d' file
Correct answer: sed '3,7d' file
In sed, address ranges use a comma to separate start and end line numbers, followed by the command letter.
Question 4: What is the effect of `chmod +x script.sh` on a script that has no execute bit set?
- Adds execute permission for owner, group, and others (Correct answer)
- Adds execute permission for the owner only
- Makes the file immutable
- Adds read and execute permissions
Correct answer: Adds execute permission for owner, group, and others
Using `+x` without specifying a user class adds execute permission to all three classes: user, group, and other.
Question 5: Which bash substitution removes the longest matching suffix pattern from a variable?
- ${var%%pattern} (Correct answer)
- ${var%pattern}
- ${var##pattern}
- ${var#pattern}
Correct answer: ${var%%pattern}
`%%` removes the longest match of the pattern from the end (suffix), while `%` removes the shortest match.
Question 6: How does `xargs -I {}` differ from plain `xargs` when constructing commands?
- It places each argument at the {} placeholder position instead of appending at the end (Correct answer)
- It ignores empty lines
- It splits arguments by character instead of whitespace
- It runs commands in parallel
Correct answer: It places each argument at the {} placeholder position instead of appending at the end
`-I {}` defines a replace-string so each input item replaces `{}` wherever it appears in the command template.
Question 7: What does `2>/dev/null` accomplish in a shell command?
- Discards all error messages (Correct answer)
- Redirects errors to stdout
- Disables the command's stderr
- Sends stderr to a log file
Correct answer: Discards all error messages
Redirecting file descriptor 2 (stderr) to `/dev/null` silently discards all error output.
Which cron field position specifies the day of the week?