Unit 4: Advanced Bash Scripting & Automation - Subjective Questions
CSC104 — It Fundamentals • Practice Questions with Detailed Answers
20 questions
Explain the concept of multi-function scripting in Bash. Describe how functions improve the organization, reusability, and maintenance of automation scripts.
Multi-function scripting means dividing a Bash script into several functions, where each function performs a specific task.
Advantages:
- Modularity: Complex operations are divided into smaller logical units.
- Reusability: A function can be called multiple times without rewriting its commands.
- Maintainability: Changes can be made to one function without affecting unrelated parts of the script.
- Readability: The main program becomes easier to understand.
- Testing: Individual functions can be tested separately.
A function can be declared using:
function_name() { commands; }
Arguments are accessed using positional parameters such as $1 and $2. A function can return an exit status using return, while command output can be captured through command substitution. Functions should use local variables where possible to avoid unintended changes to global variables.
Design and explain the structure of a robust multi-function Bash script that validates input, logs activity, handles errors, and performs a main task.
A robust multi-function Bash script should be organized into clearly defined sections:
- Interpreter declaration: Use
#!/usr/bin/env bash. - Safety options:
set -euo pipefailhelps detect errors, unset variables, and failed pipeline commands. - Configuration: Define constants, paths, and default values.
- Functions: Create separate functions such as
validate_input,log_message,handle_error, andperform_task. - Input validation: Check the number, format, and validity of arguments.
- Logging: Store timestamps, operation details, and error messages in a log file.
- Main flow: Call functions in a predictable order.
- Exit status: Return zero for success and a nonzero value for failure.
The script should also quote variables, check command availability with command -v, and use traps such as trap 'handle_error' ERR when centralized error handling is required. This structure improves reliability and makes the script easier to extend.
Describe how to create an interactive Bash menu with colors. Explain the purpose of ANSI escape sequences and discuss how user choices should be validated.
An interactive Bash menu displays a list of options, reads the user's selection, and executes the corresponding operation.
Typical steps:
- Define color variables using ANSI escape sequences, for example
\e[31mfor red and\e[32mfor green. - Reset formatting after colored output using
\e[0m. - Display menu options with
printf. - Read input using
read -r choice. - Use a
casestatement to process the selection. - Provide an exit option.
- Display an error message for invalid input.
A menu should validate that the choice is one of the permitted values. Numeric validation can be performed with a pattern such as [[ $choice =~ ^[1-4]$ ]]. The script should also handle empty input and unexpected characters gracefully. Colors improve readability, but the menu must remain understandable when color output is unsupported.
Compare the use of a case statement and nested if statements in an interactive Bash menu. Which approach is generally more suitable, and why?
Both case and if statements can implement menu selection, but they have different strengths.
Nested if statements:
- Are useful for complex Boolean conditions.
- Can test ranges, file properties, and combinations of conditions.
- Become difficult to read when many menu choices are added.
case statements:
- Match one value against several alternatives.
- Make menu logic concise and readable.
- Easily support multiple values, such as
1|start. - Provide a natural default branch using
*for invalid choices.
For an interactive menu, a case statement is generally more suitable because each menu option maps directly to one branch. Nested if statements are better when the decision depends on multiple conditions rather than one menu selection.
Explain remote script execution in Bash using SSH. Discuss authentication, quoting, environment variables, file transfer, and security precautions.
Remote script execution allows commands or scripts to run on another system through SSH.
Common approaches:
- Execute an inline command:
ssh user@host 'command'. - Send a local script to the remote shell:
ssh user@host 'bash -s' < script.sh. - Copy a script first with
scp, then execute it remotely.
Important considerations:
- Use SSH keys instead of embedding passwords in scripts.
- Verify the remote host and protect private keys with suitable permissions.
- Quote commands carefully because local and remote shells may expand variables at different times.
- Pass required values explicitly instead of assuming the remote environment matches the local environment.
- Check SSH exit statuses and use timeouts where appropriate.
- Restrict remote accounts and use least privilege.
- Avoid inserting untrusted input directly into remote commands.
Remote execution is powerful for administration, but weak authentication and unsafe command construction can expose multiple systems.
Explain how JSON data can be processed with jq in Bash. Include examples of extracting fields, filtering arrays, and producing formatted output.
jq is a command-line JSON processor that parses structured JSON without relying on fragile text-processing commands.
Extract a field:
jq '.name' data.json
Extract a nested field:
jq '.user.email' data.json
Process an array:
jq '.items[]' data.json
Filter objects:
jq '.users[] | select(.active == true)' data.json
Extract selected properties:
jq '.users[] | {name, email}' data.json
Produce compact output:
jq -c '.items[]' data.json
In Bash, JSON generated by another command can be piped to jq, for example command | jq -r '.id'. The -r option outputs raw strings without JSON quotation marks. Scripts should check whether the input is valid JSON and handle missing or null fields explicitly.
Describe how a Bash script can safely consume JSON returned by a web API. Explain the roles of curl, HTTP status checking, jq, and error handling.
A safe API-consuming script should separate network communication, response validation, and data extraction.
Recommended process:
- Use
curlwith options such as--fail,--silent, and--show-error. - Capture the response body and HTTP status code.
- Verify that the request succeeded before parsing the body.
- Use
jqto extract fields from valid JSON. - Check for API-level error objects even when the HTTP request succeeds.
- Validate that required fields are present and non-null.
- Use explicit timeouts and avoid exposing credentials in process listings or logs.
For more detailed status handling, curl -w can write the HTTP status code separately. The script should distinguish transport failures, HTTP failures, malformed JSON, and valid responses containing application errors. This prevents later commands from acting on incomplete or incorrect data.
Explain the main steps required to integrate the Cloudflare API into a Bash automation script for managing DNS records.
Cloudflare API integration generally follows these steps:
- Authentication: Use an API token with only the required permissions, such as DNS record read and edit access for a specific zone.
- Identify the zone: Retrieve or configure the zone ID.
- Construct the endpoint: Use the appropriate Cloudflare API URL and resource path.
- Set headers: Include
Authorization: Bearer TOKENandContent-Type: application/json. - Send the request: Use
curlwith the correct HTTP method, such asGET,POST,PUT, orDELETE. - Build JSON safely: Generate request data with
jq -ninstead of manually concatenating untrusted values. - Parse the response: Use
jqto check thesuccessfield and extract errors or record IDs. - Verify the result: Query the record after modification when reliable confirmation is required.
Tokens should be stored securely, excluded from source control, and never printed in logs.
Differentiate between an API token and a global API key when authenticating to Cloudflare. Why is the principle of least privilege important?
A global API key is typically associated with the entire Cloudflare account and has broad access. A scoped API token can be limited by account, zone, and operation, such as reading or editing DNS records.
API tokens are preferred because:
- They reduce the impact of accidental disclosure.
- They can be restricted to only required resources.
- They can use separate permissions for read and write operations.
- They are easier to rotate without affecting unrelated integrations.
The principle of least privilege means that a script receives only the permissions necessary to perform its task. For example, a DNS updater should not have permission to manage billing, users, or all account resources. Credentials should be kept in protected environment variables or secret stores, and scripts should avoid exposing them through command output, logs, or command-line arguments.
Design an access log summarizer using Bash tools. Explain how the script could calculate request counts, status-code frequencies, top client IP addresses, and error rates.
An access log summarizer should first identify the log format and reliably extract fields such as client IP, HTTP status, method, path, and response size.
Possible processing stages:
- Read the file line by line or process it with
awk. - Count total requests.
- Group status codes using
awk,sort, anduniq -c. - Count IP addresses and sort them numerically to identify the most active clients.
- Filter status codes in the
4xxand5xxranges to measure errors. - Calculate the error percentage as:
error rate = (number of error responses / total requests) * 100 - Produce a readable report and optionally write it to a timestamped file.
The script should handle missing files, malformed lines, empty logs, and division by zero. For complex or nonstandard formats, a parser that understands the actual log structure is safer than assuming fields based only on whitespace.
Explain how pipelines can be used to build a compact access log analysis command. Discuss the purpose of awk, sort, uniq, head, and grep in the pipeline.
A pipeline passes the standard output of one command to the standard input of the next command.
For example, a pipeline for counting HTTP status codes may conceptually use:
awkto extract the status-code field.sortto place identical values together.uniq -cto count repeated values.sort -nrto order counts from highest to lowest.headto display the most frequent results.
grep can restrict input to lines matching a pattern, such as requests containing a particular path or status family. Each command performs one focused transformation, making the overall operation easy to combine and modify.
However, field positions depend on the log format. A pipeline should be tested with representative input, and quoted patterns should be used to avoid unintended shell expansion.
Describe how to send email from a Bash script using SSMTP or an equivalent lightweight SMTP client. Include configuration, authentication, message construction, and security concerns.
A lightweight SMTP client allows a Bash script to submit email through an SMTP server.
Basic process:
- Install and configure SSMTP or a currently supported equivalent.
- Specify the SMTP host, port, TLS mode, sender identity, and authentication details.
- Construct a message containing headers such as
To,From,Subject, and a blank line before the body. - Pipe the message to the mail client using standard input.
- Check the program's exit status and log failures without exposing credentials.
A message can be created with printf or a here-document. The configuration file must be readable only by the appropriate account. Credentials should preferably be stored in a secret manager or protected configuration, and modern SMTP authentication and TLS should be used. Because SSMTP is obsolete on many systems, an actively maintained alternative may be required.
Compare pipes and redirection in Bash. Explain standard input, standard output, standard error, and the operators commonly used with each mechanism.
A pipe connects the output of one command directly to the input of another command. It is represented by |, as in producer | consumer.
Redirection changes where a command reads or writes data.
>writes standard output to a file and replaces its contents.>>appends standard output to a file.<reads standard input from a file.2>redirects standard error.2>>appends standard error.&>redirects both standard output and standard error in Bash.2>&1sends standard error to the current destination of standard output.
A pipe is primarily used to connect processing stages, while redirection is used to store, retrieve, or separate command streams. For example, command > output.txt 2> errors.txt stores normal output and errors separately.
Explain the design and security requirements of a Bash password generator. Discuss randomness, password length, character selection, and handling of generated passwords.
A secure password generator should use a cryptographically appropriate random source rather than predictable values such as timestamps or the Bash $RANDOM variable alone.
Important requirements:
- Read random bytes from
/dev/urandomor use a trusted password-generation utility. - Support a configurable length.
- Select characters from multiple classes when policy requires it, including uppercase, lowercase, digits, and symbols.
- Avoid modulo bias when mapping random bytes to a character set, or use a trusted tool that handles this correctly.
- Validate that the requested length is acceptable.
- Avoid storing passwords in unnecessary files or exposing them through logs.
- Clear sensitive variables when practical and restrict file permissions.
The generator should provide predictable command-line behavior, report invalid options, and return a failure status when it cannot obtain secure randomness.
Derive a secure workflow for generating a password and emailing it to an administrator from a Bash script. Identify the risks and controls required at each stage.
A secure workflow should minimize the time and number of locations in which the password exists.
Workflow:
- Validate configuration and recipient details.
- Generate the password using a cryptographically secure source.
- Store it only in a protected shell variable or a temporary file with restrictive permissions if necessary.
- Construct the email without writing the password to ordinary logs.
- Send the message through an authenticated TLS SMTP connection.
- Check the mail client's exit status.
- Remove temporary files and unset sensitive variables after use.
Risks and controls:
- Predictable generation: Use a secure random source.
- Credential leakage: Avoid command-line arguments, debug output, and world-readable files.
- Email interception: Use TLS, although email should not be treated as a fully confidential channel.
- Partial failure: Do not report success until delivery submission succeeds.
- Overprivileged execution: Run with the minimum account permissions needed.
For high-value credentials, secure out-of-band delivery or a secrets manager is preferable to email.
Explain the purpose of exit statuses in Bash automation. Describe how they should be used when chaining commands, pipelines, API calls, and remote execution.
Every Bash command normally returns an integer exit status. By convention, zero indicates success and a nonzero value indicates failure.
Uses in automation:
- Test a command with
if command; then ... fi. - Use
||for failure handling and&&for conditional continuation. - Inspect
$?immediately after a command when the specific status is needed. - Use
set -ecarefully to stop on unexpected failures. - Use
set -o pipefailso a failure in an earlier pipeline command is not hidden by a successful final command. - Check
sshstatus to determine whether remote execution succeeded. - Check
curlstatus and HTTP status separately because a valid network connection may still return an API error.
Scripts should return meaningful nonzero statuses and print useful diagnostic messages, allowing schedulers and monitoring tools to detect failures.
Describe the architecture of an automated WordPress installation on a LAMP stack. Identify the role of Linux, Apache, MySQL or MariaDB, PHP, and WordPress.
A LAMP-based WordPress installation consists of several cooperating layers:
- Linux: Provides the operating system, users, permissions, services, and package management.
- Apache: Accepts HTTP or HTTPS requests and serves WordPress files through a configured virtual host.
- MySQL or MariaDB: Stores WordPress posts, users, settings, metadata, and other application data.
- PHP: Executes WordPress application code and connects it to the database.
- WordPress: Provides the content-management application and its administration interface.
Automation commonly installs packages, enables Apache and PHP modules, creates a database and restricted database user, downloads and verifies WordPress, extracts it into the document root, assigns ownership, creates Apache configuration, and enables the site. The process should also configure HTTPS, firewall rules, secure file permissions, and service startup.
Develop a step-by-step plan for automating WordPress setup on a LAMP server. Include idempotency checks so that the script can be safely rerun.
A rerunnable setup script should perform the following stages:
- Check that it is running on a supported Linux distribution with required privileges.
- Install Apache, PHP, required PHP extensions, and MariaDB or MySQL only when they are absent.
- Enable and start required services, checking their status.
- Create the WordPress database and user only if they do not already exist.
- Download a verified WordPress archive into a temporary directory.
- Extract files only when the target installation is missing or incomplete.
- Set ownership and permissions according to the web server account.
- Create the Apache virtual-host configuration only if it is not already present.
- Enable the site and required rewrite module, then test the configuration before reloading Apache.
- Create a configuration file with protected database credentials.
- Record completed steps and stop safely on errors.
Idempotency means repeated execution produces the same desired state without duplicating users, database objects, configuration entries, or content.
Explain how a Bash automation script should manage secrets when configuring Cloudflare, SMTP, and WordPress database access.
Secrets include API tokens, SMTP passwords, database passwords, and private keys. They require protection throughout the script lifecycle.
Recommended practices:
- Read secrets from a protected secret manager, environment variable, or file with restrictive permissions.
- Do not hard-code secrets in scripts or commit them to source control.
- Avoid passing secrets as command-line arguments because they may appear in process listings.
- Prevent secrets from being printed by tracing, debugging, or verbose logging.
- Use separate credentials for separate services.
- Apply least-privilege permissions, such as a database user restricted to the WordPress database.
- Rotate credentials and support replacement without editing application logic.
- Protect temporary files using secure creation methods and delete them after use.
- Ensure backups and logs do not unintentionally contain credentials.
A script should also validate that required secrets are present before making changes and should fail with a safe diagnostic message when they are missing.
Explain the role of quoting and command substitution in advanced Bash scripts. Illustrate how incorrect quoting can affect remote commands, JSON data, filenames, and user input.
Quoting controls how the shell interprets spaces, wildcard characters, variables, and command substitutions.
- Double quotes: Preserve spaces and expand variables, for example
"$filename". - Single quotes: Prevent variable and command expansion, useful for passing literal remote commands.
- Unquoted variables: May undergo word splitting and pathname expansion, causing incorrect or unsafe behavior.
- Command substitution:
$(command)replaces the expression with command output.
Quoting is important when filenames contain spaces, when user input is used in commands, and when commands are sent through SSH. JSON strings should not be assembled by unsafe concatenation; jq -n can produce correctly escaped JSON. User-controlled input should be validated and passed as data where possible. Proper quoting prevents data corruption and reduces command-injection risks.
Explain the concept of multi-function scripting in Bash. Describe how functions improve the organization, reusability, and maintenance of automation scripts.
Multi-function scripting means dividing a Bash script into several functions, where each function performs a specific task.
Advantages:
- Modularity: Complex operations are divided into smaller logical units.
- Reusability: A function can be called multiple times without rewriting its commands.
- Maintainability: Changes can be made to one function without affecting unrelated parts of the script.
- Readability: The main program becomes easier to understand.
- Testing: Individual functions can be tested separately.
A function can be declared using:
function_name() { commands; }
Arguments are accessed using positional parameters such as $1 and $2. A function can return an exit status using return, while command output can be captured through command substitution. Functions should use local variables where possible to avoid unintended changes to global variables.
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 →