Unit 4: Advanced Bash Scripting & Automation - Practice Quiz

CSC104 — It Fundamentals 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the main purpose of using functions in a Bash script?

Multi-function scripting Easy
A. To install operating systems
B. To encrypt every script file automatically
C. To replace the Bash shell
D. To organize reusable commands

2 Which syntax correctly calls a Bash function named backup_files?

Multi-function scripting Easy
A. function.execute backup_files
B. backup_files
C. call: backup_files
D. run backup_files()

3 Which Bash command is commonly used to read a user's menu choice?

Interactive menu with colors Easy
A. write
B. print
C. read
D. export

4 What is commonly used to display colored text in a Bash menu?

Interactive menu with colors Easy
A. SQL query codes
B. ANSI escape codes
C. A complete graphical desktop theme stored in the script
D. HTML form tags

5 Which command is commonly used to execute commands securely on a remote Linux server?

Remote script execution Easy
A. ssh
B. zip
C. mount
D. grep

6 In the command ssh admin@example.com, what does admin represent?

Remote script execution Easy
A. The network protocol
B. The remote username
C. The script output format and remote directory
D. The local filename

7 What is jq primarily used for in shell scripts?

Working with JSON via jq Easy
A. Processing JSON data
B. Compiling Java programs
C. Formatting all types of database tables and spreadsheets
D. Managing Linux users

8 Which command extracts the name field from data.json using jq?

Working with JSON via jq Easy
A. jq '.name' data.json
B. jq ':name' data.json
C. jq 'select the name property from every document' data.json
D. jq '/name' data.json

9 What does an API token provide when a script accesses the Cloudflare API?

Cloudflare API integration Easy
A. Authentication and permissions
B. Automatic replacement of the server operating system
C. Terminal color settings
D. Local disk compression

10 Which command-line tool is commonly used to send HTTP requests to the Cloudflare API?

Cloudflare API integration Easy
A. curl
B. Aptitude package manager with every optional plugin enabled
C. chmod
D. tar

11 What information is commonly recorded in a web server access log?

Access log summarizer Easy
A. BIOS configuration values
B. Client requests and status codes
C. Desktop wallpaper settings
D. The full source code of every application on the server

12 Which command is useful for counting lines in an access log?

Access log summarizer Easy
A. pwd -l
B. wc -l
C. sort --install-and-count-all-lines
D. cd -l

13 What is SSMTP used for in a Bash automation script?

Sending emails with SSMTP Easy
A. Sending email messages
B. Creating user passwords
C. Hosting a complete interactive website directly from the terminal
D. Editing image files

14 Which piece of information identifies the server used to send email through SSMTP?

Sending emails with SSMTP Easy
A. A list of every recipient's operating system and browser version
B. File permission mask
C. SMTP host address
D. Local shell prompt

15 Which property is most important for passwords created by an automated generator?

Password generator Easy
A. They should be unpredictable
B. They should contain a complete sentence explaining the account purpose
C. They should match the username
D. They should use one repeated character

16 Which Linux source can provide random bytes for a Bash password generator?

Password generator Easy
A. /usr/share/doc/all-installed-packages
B. /var/log/syslog
C. /dev/urandom
D. /etc/hostname

17 What does the pipe operator | do in Bash?

Pipes versus redirection Easy
A. Saves output only to a file
B. Sends one command's output to another
C. Combines every file in a directory into one executable program
D. Runs a command on a remote server

18 What does > do in the command date > today.txt?

Pipes versus redirection Easy
A. Reads input from the file
B. Appends the current date while preserving every existing line
C. Pipes output to date
D. Writes output to the file

19 In the term LAMP, what does the letter A represent?

Automated WordPress setup on LAMP stack Easy
A. Apache
B. Application
C. Automation
D. Advanced administration and network protection

20 Why does an automated WordPress setup script create a database?

Automated WordPress setup on LAMP stack Easy
A. To establish an SSH connection
B. To color the Bash terminal
C. To compile the Linux kernel with WordPress-specific device drivers
D. To store WordPress content and settings

21 A Bash script defines backup_files() and show_usage(). Which approach correctly calls show_usage when the user supplies no command-line arguments?

Multi-function scripting Medium
A. [[ $1 -gt 0 ]] && show_usage
B. [[ $? -eq 0 ]] && show_usage
C. [[ $# -eq 0 ]] && show_usage
D. [[ $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?

Multi-function scripting Medium
A. get_size() { return $(du -s "$1"); }
B. get_size() { export "$1"; du -sh; }
C. get_size() { du -sh "$1" | cut -f1; }
D. 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?

Interactive menu with colors Medium
A. Print the ANSI erase sequence \e[2J
B. Print the ANSI reset sequence \e[0m
C. Run stty echo after each line
D. Run 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?

Interactive menu with colors Medium
A. An until loop with a fixed counter
B. A case statement with a * pattern
C. A for loop with a numeric range
D. A 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?

Remote script execution Medium
A. ssh admin@server1 'bash -s' < audit.sh
B. bash admin@server1 | ssh audit.sh
C. ssh admin@server1 < bash audit.sh
D. 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?

Remote script execution Medium
A. ssh user@host 'echo $HOSTNAME'
B. ssh user@host "echo $HOSTNAME"
C. ssh user@host echo \"$HOSTNAME\"
D. 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?

Working with JSON via jq Medium
A. .users[] | map(.active == true) | .name
B. .users | select(.active == true) | .name
C. .users[] | select(.active == true) | .name
D. .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?

Working with JSON via jq Medium
A. id=$(jq -c '.id' <<< "$response")
B. id=$(jq -R '.id' <<< "$response")
C. id=$(jq -s '.id' <<< "$response")
D. 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?

Cloudflare API integration Medium
A. Authentication: Basic TOKEN and Content-Type: text/plain
B. Authorization: Bearer TOKEN and Content-Type: application/json
C. Authorization: Token TOKEN and Accept: application/xml
D. 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?

Cloudflare API integration Medium
A. The API token must be replaced with the record ID
B. The zone name must be calculated from the record ID
C. The DNS value must be encoded using the record ID
D. The update endpoint identifies the record by its record ID

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?

Access log summarizer Medium
A. cut -d' ' -f1 access.log | sort -u | wc -l | head
B. awk '{print $1}' access.log | uniq -c | sort | head -n 10
C. sort -nr access.log | awk '{print $1}' | uniq | tail
D. 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?

Access log summarizer Medium
A. awk '$9 = 404 {count++} END {print count}' access.log
B. awk '$8 == 404 {count++} END {print count}' access.log
C. awk '$9 == 404 {count++} END {print count}' access.log
D. 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?

Sending emails with SSMTP Medium
A. ssmtp < recipient@example.com | message.txt
B. ssmtp message.txt > recipient@example.com
C. ssmtp message.txt | recipient@example.com
D. 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?

Sending emails with SSMTP Medium
A. if [[ -s backup.sh ]]; then ssmtp ops@example.com < failure.txt; fi
B. if ./backup.sh; then ssmtp ops@example.com < failure.txt; fi
C. if [[ $# -eq 0 ]]; then ssmtp ops@example.com < failure.txt; fi
D. 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?

Password generator Medium
A. LC_ALL=C tr -c 'A-Za-z0-9!@#%' < /dev/null | head -c 20
B. LC_ALL=C cut -c 'A-Za-z0-9!@#%' /dev/urandom | head -n 20
C. LC_ALL=C tr -dc 'A-Za-z0-9!@#%' < /dev/urandom | head -c 20
D. 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?

Password generator Medium
A. $RANDOM automatically stores every result in shell history
B. $RANDOM always produces only even decimal numbers
C. $RANDOM reads directly from a public network service
D. $RANDOM has limited state and is not cryptographically secure

37 Which statement correctly describes producer | consumer > result.txt?

Pipes versus redirection Medium
A. The redirection combines both commands before sending their output to the terminal
B. The redirection saves producer output, then the pipe reads the saved file
C. The pipe sends result.txt to producer, then consumer overwrites standard input
D. The pipe sends producer output to consumer, then redirection saves consumer output

38 A script must save both standard output and standard error from deploy.sh into deploy.log. Which Bash command performs this correctly?

Pipes versus redirection Medium
A. ./deploy.sh > deploy.log 2>&1
B. ./deploy.sh 2> deploy.log 1>&2
C. ./deploy.sh | deploy.log 2>1
D. ./deploy.sh < deploy.log 2>&1

39 During an automated WordPress installation, which database setup follows the principle of least privilege?

Automated WordPress setup on LAMP stack Medium
A. Reuse the web server account as a MySQL administrator with global rights
B. Grant an anonymous database user global privileges on all databases
C. Configure WordPress to connect permanently as the MySQL root user
D. Create a dedicated database user and grant it rights only on the WordPress database

40 An installation script may be run more than once. Which design best makes the WordPress database creation step idempotent?

Automated WordPress setup on LAMP stack Medium
A. Generate a different database name each time the script is executed
B. Drop every existing database before creating the WordPress database
C. Use CREATE DATABASE IF NOT EXISTS and conditionally create the application user
D. Ignore all MySQL errors and continue with the remaining commands

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?

Multi-function scripting Hard
A. calculate() { echo "starting"; echo 42; }
B. calculate() { printf '%s\n' "starting 42" >&1; }
C. calculate() { return 42; echo "starting" >&2; }
D. 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?

Multi-function scripting Hard
A. set -o noclobber
B. set -E
C. set -m
D. 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?

Interactive menu with colors Hard
A. [[ -n $PS1 ]] before emitting colors
B. [[ -r /dev/tty ]] before emitting colors
C. [[ $TERM != linux ]] before emitting colors
D. [[ -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?

Interactive menu with colors Hard
A. Run the menu in a pipeline so the parent terminal remains unchanged
B. Run stty echo only after read succeeds
C. Install an EXIT INT TERM trap that restores stty echo and prints the reset sequence
D. Use 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?

Remote script execution Hard
A. ssh host 'bash -s -- $arg' < task.sh
B. ssh host "bash -s -- $arg" < task.sh
C. printf -v q '%q' "$arg"; ssh host "bash -s -- $q" < task.sh
D. 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?

Remote script execution Hard
A. Use sudo -n bash -s and configure narrowly scoped passwordless sudo
B. Use ssh -t and keep the password prompt mixed with script input
C. Use bash -i -s so the remote shell handles the password prompt
D. Use 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}?

Working with JSON via jq Hard
A. sort_by(.status) | map({key: (.status | tostring), value: 1}) | unique_by(.key)
B. sort_by(.status) | group_by(.status) | map({key: (.[0].status | tostring), value: length}) | from_entries
C. map(.status) | unique | map({key: tostring, value: length}) | from_entries
D. 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?

Working with JSON via jq Hard
A. echo "$name" | jq -n '{name: input}'
B. jq -n --arg name "$name" '{name: $name}'
C. printf '{"name":"%s"}' "$name"
D. 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?

Cloudflare API integration Hard
A. curl -s -H "Authorization: Bearer $TOKEN" "$url" | jq -e .
B. curl --fail -sS -H "Authorization: Bearer $TOKEN" "$url"
C. curl -I -sS -H "Authorization: Bearer $TOKEN" "$url"
D. 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?

Cloudflare API integration Hard
A. Continue while .result_info.count < .result_info.per_page
B. Continue while .result_info.page < .result_info.total_pages
C. Continue while .success == true regardless of page metadata
D. Continue while .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?

Access log summarizer Hard
A. Run awk '{count[$9]++}' for every possible Apache and Nginx format
B. Remove all quoted text first and count the final numeric field on each line
C. Parse the documented log format with a quote-aware parser, then count the status field
D. Split each line on spaces and count the first three-digit token encountered

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?

Access log summarizer Hard
A. for f in access.log access.log.*; do [[ -e $f ]] || continue; case $f in *.gz) gzip -cd -- "$f";; *) cat -- "$f";; esac; done | summarize
B. cat access.log access.log.* | gzip -cd | summarize
C. for f in $(ls access.log*); do zcat $f; done | summarize
D. find . -name 'access.log*' -print | xargs cat | summarize

53 Which message structure is required when piping a complete email to ssmtp recipient@example.com?

Sending emails with SSMTP Hard
A. RFC-style headers, one blank line, then the message body
B. A subject line only, followed immediately by the message body
C. SMTP commands followed directly by MIME headers without a blank line
D. Message body first, one blank line, then RFC-style headers

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?

Sending emails with SSMTP Hard
A. set -o posix
B. set -o pipefail
C. set -o monitor
D. set -o noclobber

55 A password generator maps each random byte to an alphabet of size using byte % 62. Which method removes modulo bias?

Password generator Hard
A. Reject bytes at least , then reduce accepted bytes modulo 62
B. Discard bytes below 62, then divide each remaining byte by 62
C. XOR each byte with 62 before reducing the result modulo 62
D. Reduce every byte modulo 62, then shuffle the resulting password twice

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?

Password generator Hard
A. /dev/urandom returns failure after a short random read
B. head exits after 24 characters, causing upstream tr to receive SIGPIPE
C. tr -dc returns failure whenever it discards at least one byte
D. 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?

Pipes versus redirection Hard
A. The piped loop runs in a subshell; use while read -r x; do ((count++)); done < <(printf '%s\n' a b)
B. The loop receives no input; use printf '%s\n' a b > while read -r x; do ((count++)); done
C. The variable is read-only in loops; export count before starting the pipeline
D. Arithmetic expansion is delayed; use 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?

Pipes versus redirection Hard
A. command > combined.log 2>&1, because standard error duplicates the already redirected standard output
B. command 2> combined.log 1>&2, because both descriptors remain attached to the terminal
C. command | combined.log 2>&1, because a pipe opens the named file for both streams
D. 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?

Automated WordPress setup on LAMP stack Hard
A. Use CREATE DATABASE IF NOT EXISTS, ensure the user exists, and reapply the required grants
B. Drop the database on every run, recreate the user, and import WordPress again
C. Ignore every MySQL error and continue directly to the WordPress installation
D. Skip all database commands whenever 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?

Automated WordPress setup on LAMP stack Hard
A. Run all WP-CLI commands as root and recursively set the installation to mode 777
B. Run filesystem-changing WP-CLI commands as the intended site owner and assign narrowly scoped ownership
C. Keep every file owned by root and grant write access only through global ACL defaults
D. Run WP-CLI as the database user and make the document root group-independent