Unit 4: Advanced Bash Scripting & Automation - Practice Quiz
1 What is the main purpose of using functions in a Bash script?
2
Which syntax correctly calls a Bash function named backup_files?
3 Which Bash command is commonly used to read a user's menu choice?
4 What is commonly used to display colored text in a Bash menu?
5 Which command is commonly used to execute commands securely on a remote Linux server?
6
In the command ssh admin@example.com, what does admin represent?
7
What is jq primarily used for in shell scripts?
8
Which command extracts the name field from data.json using jq?
9 What does an API token provide when a script accesses the Cloudflare API?
10 Which command-line tool is commonly used to send HTTP requests to the Cloudflare API?
11 What information is commonly recorded in a web server access log?
12 Which command is useful for counting lines in an access log?
13 What is SSMTP used for in a Bash automation script?
14 Which piece of information identifies the server used to send email through SSMTP?
15 Which property is most important for passwords created by an automated generator?
16 Which Linux source can provide random bytes for a Bash password generator?
17
What does the pipe operator | do in Bash?
18
What does > do in the command date > today.txt?
date
19
In the term LAMP, what does the letter A represent?
20 Why does an automated WordPress setup script create a database?
21
A Bash script defines backup_files() and show_usage(). Which approach correctly calls show_usage when the user supplies no command-line arguments?
[[ $1 -gt 0 ]] && show_usage
[[ $? -eq 0 ]] && show_usage
[[ $# -eq 0 ]] && show_usage
[[ $0 -eq 0 ]] && show_usage
22 A function must calculate a directory size and make that value available to the calling code. Which implementation is most suitable for command substitution?
get_size() { return $(du -s "$1"); }
get_size() { export "$1"; du -sh; }
get_size() { du -sh "$1" | cut -f1; }
get_size() { local size="$1"; return; }
23 An interactive Bash menu prints colored choices, but text entered afterward remains green. Which change should be made after printing each colored line?
\e[2J
\e[0m
stty echo after each line
tput cols after each line
24
Which Bash structure most directly handles menu choices such as 1, 2, and q while also providing a response for invalid input?
until loop with a fixed counter
case statement with a * pattern
for loop with a numeric range
select statement without any branches
25
A local script named audit.sh must run on server1 without first being copied to a remote file. Which command sends it through SSH correctly?
ssh admin@server1 'bash -s' < audit.sh
bash admin@server1 | ssh audit.sh
ssh admin@server1 < bash audit.sh
scp admin@server1 audit.sh | bash
26
A remote command contains $HOSTNAME, which must be expanded by the remote shell rather than the local shell. Which command preserves it until remote execution?
ssh user@host 'echo $HOSTNAME'
ssh user@host "echo $HOSTNAME"
ssh user@host echo \"$HOSTNAME\"
ssh user@host "echo" '$HOSTNAME'
27
Given {"users":[{"name":"Ana","active":true},{"name":"Ben","active":false}]}, which jq filter prints only the name of each active user?
.users[] | map(.active == true) | .name
.users | select(.active == true) | .name
.users[] | select(.active == true) | .name
.users[].name | select(.active == true)
28
A script stores an API response in response and needs the raw string value of its .id field without JSON quotation marks. Which command should it use?
id=$(jq -c '.id' <<< "$response")
id=$(jq -R '.id' <<< "$response")
id=$(jq -s '.id' <<< "$response")
id=$(jq -r '.id' <<< "$response")
29 A script updates a Cloudflare DNS record through the API. Which combination should normally appear in the authenticated HTTP request?
Authentication: Basic TOKEN and Content-Type: text/plain
Authorization: Bearer TOKEN and Content-Type: application/json
Authorization: Token TOKEN and Accept: application/xml
X-API-Password: TOKEN and Content-Type: multipart/form-data
30 Before updating a Cloudflare DNS record, a script queries records by name. Why should it extract the record ID from the response?
31 In a standard combined Apache access log, the client IP address is the first whitespace-separated field. Which pipeline lists the ten most frequent client IPs?
cut -d' ' -f1 access.log | sort -u | wc -l | head
awk '{print $1}' access.log | uniq -c | sort | head -n 10
sort -nr access.log | awk '{print $1}' | uniq | tail
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
32 An Apache log uses combined log format, where the quoted request is fields 6 through 8 and the status code is field 9. Which command counts only HTTP 404 responses?
awk '$9 = 404 {count++} END {print count}' access.log
awk '$8 == 404 {count++} END {print count}' access.log
awk '$9 == 404 {count++} END {print count}' access.log
awk '$9 != 404 {count++} END {print count}' access.log
33
A Bash script creates a complete email containing To: and Subject: headers in message.txt. Which command submits it through SSMTP?
ssmtp < recipient@example.com | message.txt
ssmtp message.txt > recipient@example.com
ssmtp message.txt | recipient@example.com
ssmtp recipient@example.com < message.txt
34
A scheduled backup script should send an email only when backup.sh fails. Which condition correctly triggers the SSMTP command?
if [[ -s backup.sh ]]; then ssmtp ops@example.com < failure.txt; fi
if ./backup.sh; then ssmtp ops@example.com < failure.txt; fi
if [[ $# -eq 0 ]]; then ssmtp ops@example.com < failure.txt; fi
if ! ./backup.sh; then ssmtp ops@example.com < failure.txt; fi
35 Which command generates a 20-character password from letters, digits, and selected symbols using random bytes from the operating system?
LC_ALL=C tr -c 'A-Za-z0-9!@#%' < /dev/null | head -c 20
LC_ALL=C cut -c 'A-Za-z0-9!@#%' /dev/urandom | head -n 20
LC_ALL=C tr -dc 'A-Za-z0-9!@#%' < /dev/urandom | head -c 20
LC_ALL=C sort '/A-Za-z0-9!@#%/' /dev/random | tail -c 20
36
A password script uses random=$RANDOM$RANDOM and then truncates the result. What is the main security weakness of this approach?
$RANDOM automatically stores every result in shell history
$RANDOM always produces only even decimal numbers
$RANDOM reads directly from a public network service
$RANDOM has limited state and is not cryptographically secure
37
Which statement correctly describes producer | consumer > result.txt?
38
A script must save both standard output and standard error from deploy.sh into deploy.log. Which Bash command performs this correctly?
./deploy.sh > deploy.log 2>&1
./deploy.sh 2> deploy.log 1>&2
./deploy.sh | deploy.log 2>1
./deploy.sh < deploy.log 2>&1
39 During an automated WordPress installation, which database setup follows the principle of least privilege?
40 An installation script may be run more than once. Which design best makes the WordPress database creation step idempotent?
CREATE DATABASE IF NOT EXISTS and conditionally create the application user
41
A Bash function must compute a value for command substitution while also reporting diagnostics. Which implementation preserves the computed output in result=$(calculate) without mixing diagnostics into it?
calculate() { echo "starting"; echo 42; }
calculate() { printf '%s\n' "starting 42" >&1; }
calculate() { return 42; echo "starting" >&2; }
calculate() { echo "starting" >&2; printf '%s\n' 42; }
42
A script enables set -e and defines an ERR trap, but failures inside called functions do not consistently trigger the trap. Which additional setting makes the ERR trap inherited by shell functions, command substitutions, and subshells?
set -o noclobber
set -E
set -m
set -C
43 An interactive colored menu is also executed by cron, where its output is redirected to a log. Which condition should control whether ANSI color sequences are emitted?
[[ -n $PS1 ]] before emitting colors
[[ -r /dev/tty ]] before emitting colors
[[ $TERM != linux ]] before emitting colors
[[ -t 1 ]] before emitting colors
44
A menu temporarily disables terminal echo while reading a secret. Pressing Ctrl+C sometimes leaves the terminal unusable and colored output unreset. Which design most reliably restores both states?
stty echo only after read succeeds
EXIT INT TERM trap that restores stty echo and prints the reset sequence
read -r and print the reset sequence before disabling echo
45
A local script must pass an arbitrary argument, including spaces and shell metacharacters, to bash -s on a remote Bash host. Which pattern safely constructs the remote command?
ssh host 'bash -s -- $arg' < task.sh
ssh host "bash -s -- $arg" < task.sh
printf -v q '%q' "$arg"; ssh host "bash -s -- $q" < task.sh
ssh host bash -s -- "$arg" < task.sh
46
The command ssh host 'sudo bash -s' < deploy.sh hangs because remote sudo requests a password while standard input already carries the script. For unattended automation, which change is most appropriate?
sudo -n bash -s and configure narrowly scoped passwordless sudo
ssh -t and keep the password prompt mixed with script input
bash -i -s so the remote shell handles the password prompt
sudo -S bash -s and prepend the password to deploy.sh
47
Given an array of request objects, which jq filter returns one object mapping each HTTP status to its occurrence count, such as {"200": 8, "404": 2}?
sort_by(.status) | map({key: (.status | tostring), value: 1}) | unique_by(.key)
sort_by(.status) | group_by(.status) | map({key: (.[0].status | tostring), value: length}) | from_entries
map(.status) | unique | map({key: tostring, value: length}) | from_entries
group_by(.status) | map({(.status): length}) | add
48
A shell variable name may contain quotes, newlines, or backslashes. Which command safely creates the JSON object {"name": <value>} without manual escaping?
echo "$name" | jq -n '{name: input}'
jq -n --arg name "$name" '{name: $name}'
printf '{"name":"%s"}' "$name"
jq -n "{name: \"$name\"}"
49
A script calls the Cloudflare API with curl, and an HTTP 400 response still leaves curl with exit status 0. Which invocation best lets the script capture the JSON error body while also treating HTTP errors as command failures?
curl -s -H "Authorization: Bearer $TOKEN" "$url" | jq -e .
curl --fail -sS -H "Authorization: Bearer $TOKEN" "$url"
curl -I -sS -H "Authorization: Bearer $TOKEN" "$url"
curl --fail-with-body -sS -H "Authorization: Bearer $TOKEN" "$url"
50
A zone has more DNS records than the API's per_page limit. Which termination condition correctly drives a pagination loop using Cloudflare's result_info metadata?
.result_info.count < .result_info.per_page
.result_info.page < .result_info.total_pages
.success == true regardless of page metadata
.result | length == .result_info.total_count
51 In a standard combined access log, the request and user-agent fields contain spaces inside quotes. Which strategy most reliably counts response status codes without assuming that every whitespace-separated field has a fixed position?
awk '{count[$9]++}' for every possible Apache and Nginx format
52
A summarizer must process access.log plus rotated files ending in .gz as one stream. Which Bash pattern handles filenames safely and decompresses only the compressed files?
for f in access.log access.log.*; do [[ -e $f ]] || continue; case $f in *.gz) gzip -cd -- "$f";; *) cat -- "$f";; esac; done | summarize
cat access.log access.log.* | gzip -cd | summarize
for f in $(ls access.log*); do zcat $f; done | summarize
find . -name 'access.log*' -print | xargs cat | summarize
53
Which message structure is required when piping a complete email to ssmtp recipient@example.com?
54
A backup script uses generate_report | ssmtp admin@example.com, but with default pipeline semantics it can report success when generate_report fails and ssmtp exits successfully. Which setting makes the pipeline fail when either stage fails?
set -o posix
set -o pipefail
set -o monitor
set -o noclobber
55
A password generator maps each random byte to an alphabet of size using byte % 62. Which method removes modulo bias?
56
A generator runs tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24 under set -o pipefail. It sometimes reports failure despite producing 24 characters. What is the most likely cause?
/dev/urandom returns failure after a short random read
head exits after 24 characters, causing upstream tr to receive SIGPIPE
tr -dc returns failure whenever it discards at least one byte
head -c returns failure whenever its input is not valid UTF-8
57
Why does count=0; printf '%s\n' a b | while read -r x; do ((count++)); done; echo "$count" commonly print 0 in Bash, and which rewrite preserves the updates?
while read -r x; do ((count++)); done < <(printf '%s\n' a b)
printf '%s\n' a b > while read -r x; do ((count++)); done
count before starting the pipeline
count=$((count + 1)) inside the same pipeline
58
Which command sends both standard output and standard error to combined.log, replacing the file, and why is redirection order significant?
command > combined.log 2>&1, because standard error duplicates the already redirected standard output
command 2> combined.log 1>&2, because both descriptors remain attached to the terminal
command | combined.log 2>&1, because a pipe opens the named file for both streams
command 2>&1 > combined.log, because standard output duplicates the already redirected standard error
59 An automated WordPress installer may be rerun after a partial failure. Which database provisioning approach is most idempotent?
CREATE DATABASE IF NOT EXISTS, ensure the user exists, and reapply the required grants
wp-config.php already exists
60 A root-run setup script downloads WordPress and executes WP-CLI. Which practice best avoids later ownership and permission failures when WordPress performs updates through the web server account?
777
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →