Courseiva

CCNA Lxp Scripting Containers Questions

75 of 112 questions · Page 1/2 · Lxp Scripting Containers topic · Answers revealed

1
MCQhard

An administrator is managing a Kubernetes cluster. A pod is running but not responding as expected. The administrator wants to view the standard output logs from the pod's main container. Which kubectl command should be used?

A.kubectl exec <pod-name> -- cat /var/log/app.log
B.kubectl get pod <pod-name> -o yaml
C.kubectl describe pod <pod-name>
D.kubectl logs <pod-name>
AnswerD

kubectl logs retrieves stdout and stderr written by the pod's main container, satisfying the requirement to view standard output. Other verbs such as describe or exec do not stream container logs, so they fail the stated constraint.

Why this answer

The kubectl logs <pod-name> command retrieves the standard output (stdout) and standard error (stderr) logs from a pod's container, which is exactly what the administrator needs. By default it targets the main container; if multiple containers exist, -c <container> specifies one. This is the standard way to view application logs without exec'ing into the container.

Exam trap

The trap is assuming logs live in a file inside the container — candidates pick exec + cat, but Kubernetes captures stdout/stderr, and kubectl logs is the canonical command.

How to eliminate wrong answers

Option A is wrong because kubectl exec runs a command inside the container; cat /var/log/app.log assumes the app writes to that file, which is not guaranteed and does not retrieve the container's stdout stream. Option B is wrong because kubectl get pod -o yaml returns the pod's YAML manifest (spec and status), not runtime logs. Option C is wrong because kubectl describe pod shows events, conditions, and metadata about the pod, useful for troubleshooting scheduling or image pull issues, but not application stdout logs.

2
MCQeasy

A Linux administrator needs a cron job that runs /usr/local/bin/collect.sh at 02:30 every Monday, Wednesday, and Friday. The job must be added for the root user without editing the global /etc/crontab file. Which command should the administrator run to open the correct crontab for editing?

A.crontab -l -u root
B.systemctl edit cron
C.crontab -u root -e
D.crontab -e
AnswerC

The -u flag selects the user whose crontab is being edited, so this command always opens root's personal crontab regardless of which account is currently logged in. Entries placed there are executed as root, and the schedule field can specify 30 2 * * 1,3,5 to meet the Monday, Wednesday, and Friday requirement.

Why this answer

The crontab command with the -u option edits the named user's personal crontab, so crontab -u root -e reliably opens root's schedule for modification from any account with the needed privilege. The schedule line 30 2 * * 1,3,5 then executes collect.sh at 02:30 on Monday, Wednesday, and Friday, fulfilling the requirement without touching /etc/crontab.

Exam trap

The trap here is assuming that crontab -e always edits root's table, when it actually targets whichever user invokes it.

3
MCQeasy

A Linux administrator needs to extract the value of the 'version' field from a JSON file named config.json. The file contains a top-level key 'version' with a string value. Which command should be used to retrieve just the value?

A.jq -r '.version' config.json
B.grep '"version"' config.json
C.sed -n 's/.*"version": *"\(.*\)".*/\1/p' config.json
D.awk -F'"' '/version/ {print $4}' config.json
AnswerA

`jq` is a lightweight and flexible command-line JSON processor. The `-r` option outputs raw strings without quotes. The filter `.version` extracts the value of the top-level 'version' key. This is the correct and reliable way to parse JSON and retrieve a specific field's value, handling formatting and escaping properly.

Why this answer

`jq` is designed specifically for parsing JSON. Using `jq -r '.version'` extracts the value of the 'version' key and outputs it as a raw string. This approach is robust and handles JSON syntax correctly.

Other tools like `grep`, `sed`, or `awk` are text-based and may work in simple cases but are error-prone with JSON's structure and variations.

Exam trap

The trap here is using text-processing tools like `grep` or `awk` for JSON, which can fail when the JSON format changes or contains nested data.

4
Multi-Selectmedium

A system administrator is writing a Bash script that must check if a file exists and is readable. Which two test expressions can be used to achieve this? (Choose two.)

Select 2 answers
A.-e /path/to/file
B.-s /path/to/file
C.-r /path/to/file
D.-x /path/to/file
E.-f /path/to/file
AnswersA, C

The -e unary test operator returns true when the pathname resolves to an existing file or directory, regardless of type. It satisfies the existence half of the stem's requirement, letting the script confirm the file is present before attempting any read operation.

Why this answer

Option A, `-e /path/to/file`, is correct because the `-e` test in Bash returns true if the file exists, regardless of its type (regular file, directory, device, etc.), which satisfies the existence check. Option C, `-r /path/to/file`, is correct because the `-r` test returns true if the file exists and the current user has read permission on it, satisfying the readability check. Together, `-e` and `-r` cover the two required conditions of existence and readability.

Option B, `-s`, only checks that the file exists and has a size greater than zero, so it does not verify readability. Option D, `-x`, checks for execute permission rather than read permission, so it does not meet the requirement. Option E, `-f`, only checks that the path exists and is a regular file, not that it is readable.

Exam trap

The trap is assuming -f or -s implies readability; -f only checks regular-file type and -s only checks non-zero size, so neither validates the 'readable' requirement.

5
MCQmedium

An Ansible playbook includes a handler that restarts a service when a configuration file is changed. Which directive in a task triggers the handler?

A.register:
B.when:
C.handlers:
D.notify:
AnswerD

The notify directive names the handler to trigger when a task reports changed state, so a config-file modification notifies the restart handler. Handlers run once at play end, avoiding repeated service restarts during the play.

Why this answer

In Ansible, a task uses the notify: directive to name one or more handlers that should be triggered when that task reports a change (i.e., when the task's state is 'changed'). Handlers then run once at the end of the play, in the order they were notified, only if at least one notifying task changed.

Exam trap

The trap is confusing register: (capture output) or when: (conditional execution) with notify:, which is the only directive that actually triggers a handler.

How to eliminate wrong answers

Option A is wrong because register: captures a task's return values into a variable for later use — it does not trigger handlers. Option B is wrong because when: is a conditional that decides whether a task runs at all, based on a Jinja2 expression; it does not invoke handlers. Option C is wrong because handlers: is the top-level play keyword that defines the handler section, not a task-level directive that triggers one.

6
MCQeasy

A Linux administrator schedules a maintenance script with cron using the entry `30 2 * * 1 /usr/local/bin/backup.sh`. The script runs but produces no output and fails silently when executed by cron, though it works when run interactively. Which action best addresses the silent failure?

A.Move the script to `/etc/cron.d/` so it inherits the system environment.
B.Redirect the script's stdout and stderr to a log file within the crontab entry or script.
C.Add the `nohup` command before the script path in the crontab line.
D.Change the schedule to run every minute so the failure is observed sooner.
AnswerB

Cron captures any output and mails it, but if mail is unconfigured the output is discarded, so failures go unnoticed. Redirecting stdout and stderr to a file captures cron's environment-specific errors, such as missing PATH entries or permissions, enabling diagnosis. This directly resolves the lack of visibility that makes the cron run appear to fail silently.

Why this answer

Cron runs jobs with a minimal environment and no terminal, so interactive successes can become silent failures. Because cron only emails output when a mail transfer agent is configured, failures frequently vanish. Capturing stdout and stderr to a log file exposes the environment-related errors, such as an incomplete PATH or missing variables, that cause the discrepancy between interactive and scheduled execution.

Exam trap

The trap here is believing that moving a cron job's location or adding `nohup` fixes environment-related failures rather than capturing their output.

7
MCQmedium

A container is running a web server on port 8080 internally, and the administrator wants to access it on the host on port 80. Which Docker run option accomplishes this?

A.-p 80:8080
B.-P
C.-p 8080:80
D.--expose 8080
AnswerA

Publishing with `-p 80:8080` maps host port 80 to container port 8080, satisfying the requirement to reach the internal web server on the host's privileged HTTP port. Docker's port syntax is host:container, so the left value is the externally exposed port and the right is the container's listening port.

Why this answer

The Docker -p flag maps a host port to a container port using the syntax -p HOST_PORT:CONTAINER_PORT. Since the container listens on 8080 internally and the administrator wants it reachable on host port 80, the correct mapping is -p 80:8080. This publishes the container's port 8080 to the host's port 80.

Exam trap

The trap here is reversing the -p syntax — candidates frequently write -p 8080:80 thinking the container port comes first, but Docker always expects HOST_PORT:CONTAINER_PORT.

How to eliminate wrong answers

Option B is wrong because -P (capital P) publishes all exposed ports to random ephemeral host ports, which does not guarantee port 80. Option C is wrong because -p 8080:80 reverses the mapping, publishing container port 80 to host port 8080, which does not match the requirement. Option D is wrong because --expose only documents a port for inter-container communication and does not publish it to the host at all.

8
MCQhard

A system administrator wants to create a bind mount in Docker to share a host directory `/data` with a container at `/mnt/data`. Which of the following docker run options should be used?

A.-v /data:/mnt/data
B.--mount type=volume,source=/data,target=/mnt/data
C.-v /data:ro
D.-v /mnt/data:/data
AnswerA

The `-v /data:/mnt/data` flag creates a bind mount by mapping an absolute host path to a container path, satisfying the requirement to share `/data` at `/mnt/data`. Docker interprets the leading slash as a host filesystem location rather than a named volume, giving the container direct read-write access to that directory.

Why this answer

The -v /data:/mnt/data option creates a bind mount by mapping the host directory /data to the container path /mnt/data, which is exactly the requirement. Docker interprets a host path on the left of the colon as a bind mount, distinguishing it from a named volume. This is the classic syntax for sharing a host directory with a container.

Exam trap

The trap is confusing the -v shorthand with --mount syntax — candidates pick the --mount option assuming it is 'more modern,' but type=volume is wrong for a host-directory bind mount, which requires type=bind.

How to eliminate wrong answers

Option B is wrong because --mount type=volume declares a named volume, not a bind mount — for a bind mount the correct syntax is --mount type=bind,source=/data,target=/mnt/data, and using type=volume with a host path will fail or create an unexpected volume. Option C is wrong because -v /data:ro specifies only a container path with read-only mode, missing the host path entirely, so it does not create the intended bind mount. Option D is wrong because -v /mnt/data:/data reverses the source and target, mounting the host's /mnt/data into the container at /data, which is the opposite of what was requested.

9
MCQeasy

A user wants to run a Docker container in detached mode, remove it automatically after it stops, and map host port 8080 to container port 80. Which command accomplishes this?

A.docker run -d --rm -p 8080:80 image
B.docker run -it --rm -p 80:8080 image
C.docker create --rm -p 8080:80 image
D.docker start -d -p 8080:80 image
AnswerA

The -d flag detaches the container, --rm deletes it automatically once stopped, and -p 8080:80 publishes host port 8080 to container port 80. All three stem constraints are satisfied in a single command, with the image name supplied last as the positional argument.

Why this answer

The `docker run` command is the correct choice because it combines container creation and startup in a single step. The `-d` flag runs the container in detached mode (in the background), `--rm` automatically removes the container filesystem when it exits, and `-p 8080:80` maps host port 8080 to container port 80. Together these flags satisfy all three requirements in one command.

Exam trap

The trap here is confusing `docker create` with `docker run` and assuming `docker start` can apply port mappings — candidates often forget that port bindings and `--rm` are fixed at container creation time and cannot be added later.

How to eliminate wrong answers

Option B is wrong because `-it` allocates an interactive TTY and keeps the container attached to the terminal, which is the opposite of detached mode, and it also reverses the port mapping to `80:8080`. Option C is wrong because `docker create` only creates the container without starting it, and `--rm` is not a valid flag for `docker create` in that context. Option D is wrong because `docker start` is used to restart an existing stopped container and does not accept `-p` port mapping or `-d` in the same way `docker run` does; port mappings must be specified at creation time.

10
MCQeasy

A Linux administrator wants to ensure a bash script stops execution immediately if any command fails. Which line should be added to the script?

A.set -x
B.set -u
C.set -e
D.set -o pipefail
AnswerC

`set -e` makes bash exit immediately when any command returns a non-zero status, satisfying the requirement that the script halt on first failure. Unlike `set -u` (unset variables) or `set -x` (trace output), it targets command failure directly, preventing subsequent commands from running after an error.

Why this answer

`set -e` instructs bash to exit immediately if any command returns a non-zero exit status, which is exactly the fail-fast behavior the administrator wants. This prevents subsequent commands from running after a failure, avoiding cascading errors in scripts. It is the standard idiom for making bash scripts robust in automation and CI environments.

Exam trap

The trap is that candidates confuse the four `set` flags — especially `set -u` (unset variable check) and `set -o pipefail` (pipeline exit status) — with `set -e`, which is the only one that provides the general 'exit on any command failure' behavior.

How to eliminate wrong answers

Option A is wrong because `set -x` enables trace mode, printing each command and its arguments to stderr before execution — it is a debugging aid, not an error-handling mechanism. Option B is wrong because `set -u` treats unset variables as an error and exits, which catches typos in variable names but does not stop execution on general command failures. Option D is wrong because `set -o pipefail` only changes the exit status of a pipeline to reflect the rightmost non-zero command; by itself it does not cause the script to exit on failure unless combined with `set -e`.

11
Multi-Selectmedium

A Linux administrator is packaging an internal automation tool as a container image and must ensure the resulting image is minimal, reproducible, and does not include a shell or package manager. Which TWO practices best support that goal? (Choose two.)

Select 2 answers
A.Build the application as a static binary and copy it into a scratch or distroless base image
B.Add a RUN apk add --no-cache bash step so operators can exec into the container for debugging
C.Tag the image as latest and rebuild it nightly from the moving base image to keep it current
D.Run the container as root so the entrypoint can install missing packages at startup
E.Use a multi-stage Dockerfile where the builder stage compiles the tool and the final stage copies only the artifact
AnswersA, E

A static binary needs no shared libraries, so it can run on a base image that contains no shell, package manager, or libc. This shrinks the attack surface and image size while making the runtime contents deterministic, which directly matches the requirement to exclude a shell and package manager from the shipped image.

Why this answer

Minimal container images combine a static or self-contained artifact with a base image that ships no shell or package manager, and multi-stage builds keep all compilation tooling out of the final layer. Together these practices produce small, reproducible images whose contents are limited to what the application needs at runtime, with no interactive tooling available to an attacker.

Exam trap

The trap here is treating a debugging shell or nightly rebuild as harmless convenience, when both quietly violate the minimal and reproducible image requirements.

12
MCQeasy

A Linux administrator is configuring a systemd timer to run a maintenance script daily. The administrator creates maint.service and maint.timer unit files, then runs systemctl start maint.timer. The script does not run at the expected time. Which command should the administrator run to enable the timer so it starts automatically at boot and triggers on schedule?

A.systemctl reload maint.timer
B.systemctl enable maint.service
C.systemctl enable maint.timer
D.systemctl daemon-reexec
AnswerC

Enabling a timer creates the symlink needed for it to be started at boot by systemd, allowing its schedule to fire reliably. Starting a timer only activates it for the current session; enabling ensures persistence across reboots, which is required for a recurring daily maintenance task in this scenario.

Why this answer

A systemd timer must be enabled, not merely started, to be activated at boot. Enabling creates the appropriate symlink in the timer's target directory so systemd starts it automatically, and the timer then triggers the associated service according to its OnCalendar or OnUnitActiveSec schedule. Enabling the service or reloading the unit does not achieve persistent scheduled execution.

Exam trap

The trap here is confusing systemctl start, which activates a unit only for the current session, with systemctl enable, which ensures the unit starts at boot.

13
MCQeasy

Which of the following is a key difference between Docker and Podman?

A.Docker does not support container images.
B.Podman can run containers without root privileges.
C.Podman requires a daemon to run containers.
D.Docker can only run on Linux.
AnswerB

Rootless mode is Podman's defining architectural difference: it uses user namespaces to map the container's root to an unprivileged host UID, so no daemon runs as root. Docker's daemon typically requires root, making this the key security distinction the question targets.

Why this answer

Podman is a daemonless container engine that supports rootless mode, allowing unprivileged users to run containers without requiring a long-running root daemon. This is a fundamental architectural difference from Docker, which traditionally relies on a root-owned `dockerd` daemon. Rootless containers improve security by reducing the attack surface and limiting privilege escalation.

Exam trap

The trap is assuming Podman also needs a daemon like Docker, or that Docker is Linux-only — candidates who have only used Docker Desktop on macOS may incorrectly believe Docker is cross-platform while Podman is not, when the opposite architectural distinction (daemonless/rootless) is the real differentiator.

How to eliminate wrong answers

Option A is wrong because Docker absolutely supports container images — it popularized the OCI image format and Docker Hub. Option C is wrong because Podman is specifically designed to run without a daemon; it forks container processes directly, unlike Docker's client-server model. Option D is wrong because Docker runs on Windows and macOS in addition to Linux (via Docker Desktop and WSL2), so claiming Linux-only is factually incorrect.

14
MCQmedium

An administrator wants to use Ansible to ensure a service is running on a remote host. Which Ansible module should be used in a playbook?

A.service
B.command
C.copy
D.shell
AnswerA

The service module manages systemd, sysvinit and similar service managers on the remote host, letting the playbook assert that a named service is started and enabled. It is the purpose-built module for service state, unlike command or shell, which would run arbitrary commands without idempotent state guarantees.

Why this answer

The Ansible 'service' module is designed to manage services on remote hosts — starting, stopping, restarting, and enabling them. To ensure a service is running, you use 'service' with state: started (and optionally enabled: yes). It abstracts underlying init systems (systemd, SysV, upstart) so the playbook works across distributions.

Exam trap

XK0-006 often tests module selection by scenario — candidates confuse 'command'/'shell' (arbitrary execution, non-idempotent) with 'service' (idempotent service state management), picking command because it 'can run systemctl'.

How to eliminate wrong answers

Option B is wrong because the 'command' module executes arbitrary commands on the remote host but does not manage service state idempotently — running 'systemctl start foo' via command would report changed every time and lacks service-specific parameters like enabled. Option C is wrong because the 'copy' module transfers files from the control node to the remote host; it has nothing to do with service management. Option D is wrong because the 'shell' module runs commands through a shell (supporting pipes/redirection) but, like command, is not idempotent for service management and does not understand service states.

15
MCQmedium

An administrator needs to create a Docker image from a Dockerfile located in the current directory and tag it as 'myapp:v1'. Which command should be used?

A.docker create -t myapp:v1 .
B.docker commit myapp:v1 .
C.docker build -t myapp:v1 .
D.docker image create myapp:v1 .
AnswerC

docker build reads the Dockerfile from the specified context, and the dot sets the current directory as that context. The -t flag assigns the repository and tag myapp:v1, satisfying both the build-from-current-directory and tagging requirements in one command.

Why this answer

The correct command is `docker build -t myapp:v1 .` because `docker build` reads a Dockerfile from the specified context (the `.` means the current directory) and builds an image. The `-t` flag tags the resulting image with the name and tag `myapp:v1`. This is the standard way to create an image from a Dockerfile.

Exam trap

XK0-006 often tests the distinction between image creation commands: candidates may confuse `docker build` with `docker create` or `docker commit`, or mistakenly think `docker image create` is valid.

How to eliminate wrong answers

Option A is wrong because `docker create` creates a new container from an existing image; it does not build an image from a Dockerfile. Option B is wrong because `docker commit` creates a new image from a container's changes, not from a Dockerfile. Option D is wrong because `docker image create` is not a valid Docker command; the correct subcommand for building is `docker build` (or `docker image build` in newer versions, but `docker image create` does not exist).

16
MCQmedium

A Linux administrator uses Ansible to manage a fleet of servers and needs to ensure a configuration file is present with specific contents on all web servers, restarting the service only when the file changes. Which Ansible module and handler pattern accomplishes this?

A.Use the `file` module with `state: touch` and a `cron` job to restart the service periodically
B.Use the `template` module with `force: no` and no handler, relying on the service to reload automatically
C.Use the `copy` module with a `notify` directive that triggers a handler containing the `service` module with `state: restarted`
D.Use the `shell` module to run `systemctl restart httpd` after writing the file with a `command` task
AnswerC

The `copy` module places the file with the specified content and reports a changed status only when the content differs. The `notify` directive then triggers the named handler, which uses the `service` module to restart the web service. This ensures the restart occurs only on change, matching the requirement exactly.

Why this answer

Idempotent configuration management requires a module that reports change status and a handler that reacts to that status. The `copy` module writes the file and reports changed only on difference, and the `notify` directive invokes a handler that restarts the service. Unconditional shell restarts, `force: no`, or timestamp-only modules all fail to deliver a restart triggered specifically by a content change.

Exam trap

The trap here is assuming that restarting the service in the same task or unconditionally is equivalent to using a handler, which only fires on change.

17
Multi-Selectmedium

A bash script uses a loop to iterate over files in a directory. Which TWO of the following loop constructs will correctly iterate over each .txt file in the current directory? (Select TWO).

Select 2 answers
A.for file in '*.txt'; do
B.for file in $(ls *.txt); do
C.for file in *.txt; do
D.for ((i=0; i<${#files[@]}; i++)); do
E.while IFS= read -r file; do done < <(find . -maxdepth 1 -name '*.txt')
AnswersC, E

Glob expansion by the shell resolves `*.txt` into a list of matching filenames before the loop runs, so each iteration assigns one filename to `file`. This satisfies the requirement to iterate over every .txt file in the current directory, provided matches exist.

Why this answer

Option C is correct because `for file in *.txt; do` relies on bash pathname expansion (globbing), which expands the unquoted pattern `*.txt` into the list of matching filenames in the current directory, iterating over each one. Option E is correct because `while IFS= read -r file; do ... done < <(find . -maxdepth 1 -name '*.txt')` uses process substitution to feed find's output into the loop; `IFS=` preserves leading/trailing whitespace and `read -r` prevents backslash interpretation, and `find . -maxdepth 1 -name '*.txt'` lists only .txt files directly in the current directory. Option A is wrong because quoting `'*.txt'` suppresses globbing, so the loop runs once with the literal string `*.txt`.

Option B is wrong because parsing `ls` output is fragile and breaks on filenames containing spaces, newlines, or glob characters. Option D is wrong because it iterates over indices of a `files` array that is never populated in the scenario, so it does not iterate over the .txt files.

Exam trap

XK0-006 often tests the difference between quoted and unquoted globs, and the danger of parsing ls output — candidates frequently pick $(ls *.txt) thinking it is equivalent to globbing, when it is actually a word-splitting hazard.

18
MCQhard

A Linux administrator needs to parse a structured configuration file and extract the value of a specific key. The file format is JSON, and the administrator wants to use a command-line tool that is commonly preinstalled on modern Linux distributions. Which command should the administrator use?

A.jq
B.awk
C.grep
D.sed
AnswerA

jq is a lightweight command-line JSON processor that is widely available in distribution repositories and is often preinstalled on modern systems. It can parse JSON, filter with expressions such as .key, and output the value, which directly satisfies the requirement to extract a specific key from a structured JSON file.

Why this answer

jq is purpose-built for JSON, understands the format's structure, and is commonly available on modern Linux distributions. It can extract a specific key with a simple filter and correctly handles nested data, escaping, and type conversions, making it the appropriate choice for parsing a JSON configuration file.

Exam trap

The trap here is assuming that general-purpose text tools like sed, awk, or grep can reliably parse JSON, when their line-oriented nature breaks on nested or formatted JSON.

19
MCQmedium

A Bash script contains the following line: set -e. What is the effect of this command?

A.It enables debugging by printing commands and their arguments as they are executed.
B.It prevents the script from overwriting existing files.
C.It causes the script to exit if any command fails.
D.It treats unset variables as an error and exits.
AnswerC

The set -e option sets errexit, so Bash terminates the script immediately when any command returns a non-zero exit status. This satisfies the requirement to halt execution on failure rather than continuing through subsequent commands.

Why this answer

set -e causes the script to exit immediately if any command exits with a non-zero status. This is useful for catching errors early.

20
MCQeasy

In bash, what is the difference between single quotes and double quotes?

A.Single quotes prevent variable expansion, double quotes allow it.
B.Both allow variable expansion, but double quotes also allow globbing.
C.Single quotes allow variable expansion, double quotes do not.
D.There is no difference; they are interchangeable.
AnswerA

Single quotes treat every character literally, so a variable such as $HOME is passed unchanged, whereas double quotes permit parameter and variable expansion, command substitution and escape sequences. This quoting distinction determines whether the shell interprets the enclosed text before passing it to the command.

Why this answer

Single quotes preserve the literal value of each character, while double quotes allow variable expansion and command substitution.

21
Multi-Selectmedium

An administrator is troubleshooting a Pod in a Kubernetes cluster that is not starting. Which TWO kubectl commands are most useful for diagnosing the issue? (Choose TWO.)

Select 2 answers
A.kubectl get nodes
B.kubectl apply -f pod.yaml
C.kubectl delete pod <pod-name>
D.kubectl logs <pod-name>
E.kubectl describe pod <pod-name>
AnswersD, E

`kubectl logs <pod-name>` retrieves stdout/stderr from the Pod's containers, exposing application-level failures such as crash loops, misconfiguration or missing dependencies that block startup. When a Pod is running but not Ready, or restarting repeatedly, container output pinpoints the fault directly, satisfying the need to diagnose why the Pod fails to start.

Why this answer

kubectl describe pod provides detailed event and status information, and kubectl logs retrieves container logs.

22
Multi-Selecthard

A Linux administrator is writing a Bash script that must parse command-line options, accept a required input file argument, and provide a help message when invoked with -h. The script will be run on several distributions. Which TWO practices should the administrator follow? (Choose two.)

Select 2 answers
A.Hard-code the input file path inside the script so the required argument is always available.
B.Use getopts to process short options and validate that required arguments are present before proceeding.
C.Rely on the positional parameters $1 and $2 directly and check only that $# is greater than zero.
D.Use getopt (the external utility) with the long-option form and eval to reorder arguments before parsing.
E.Define a usage function that prints to standard error and exits with a non-zero status when arguments are invalid.
AnswersB, E

getopts is a POSIX shell builtin that parses short options consistently across shells and distributions. It sets OPTARG for options that take a value and OPTIND for the next argument, so the script can detect missing required arguments and print usage before doing any work. This meets the portability and validation goals in the scenario.

Why this answer

Portable option parsing and clear error handling are the two practices that make the script usable across distributions. getopts handles short options and required arguments in a POSIX-compliant way, while a dedicated usage function standardizes the help and error output. Together they ensure -h works, missing arguments are detected, and failures are reported through exit status.

Exam trap

The trap here is assuming the external getopt utility is fully portable and safe to eval, when the shell builtin getopts is the portable standard for short options.

23
MCQeasy

A Linux administrator needs to write a Bash script that runs a series of commands and stops immediately if any command fails. Which directive should be included at the beginning of the script?

A.#!/bin/bash
B.trap ... ERR
C.set -e
D.set -x
AnswerC

set -e makes Bash exit immediately when any command returns a non-zero status, so the script halts on the first failure. Placed at the top, it satisfies the requirement to stop immediately rather than continue executing subsequent commands.

Why this answer

The set -e directive (also written set -o errexit) instructs Bash to exit immediately if any command returns a non-zero exit status. Placing it at the top of a script ensures the script halts on the first failure rather than continuing with potentially harmful subsequent commands. This is the standard idiom for fail-fast Bash scripts.

Exam trap

The trap is confusing set -e (exit on error) with set -x (trace commands) or with trap ERR (custom error handler) — candidates must remember that only set -e provides the immediate-exit behavior the question requires.

How to eliminate wrong answers

Option A is wrong because #!/bin/bash is the shebang line that specifies the interpreter; it does not affect error handling. Option B is wrong because trap ... ERR sets a handler to run on error but does not by itself cause the script to exit — it requires additional logic such as 'trap "exit 1" ERR'.

Option D is wrong because set -x enables command tracing for debugging, printing each command before execution, but does not stop execution on failure.

24
MCQhard

A Kubernetes administrator needs to expose a deployment named 'web-app' running on port 80 internally within the cluster. Which kubectl command creates a service of type ClusterIP that maps port 80 to the target port 8080 on the pods?

A.kubectl create service nodeport web-app --tcp=80:8080
B.kubectl expose deployment web-app --port=80 --target-port=8080
C.kubectl expose pod web-app --port=80 --target-port=8080
D.kubectl create service clusterip web-app --tcp=80:8080
AnswerB

`kubectl expose deployment web-app --port=80 --target-port=8080` generates a ClusterIP service, the default type, satisfying the internal-only requirement. The `--port` flag sets the service port to 80, while `--target-port=8080` directs traffic to the container's listening port, correctly mapping the mismatch between service and pod ports.

Why this answer

The command 'kubectl expose deployment web-app --port=80 --target-port=8080' creates a Service of type ClusterIP (the default) that exposes the deployment 'web-app'. The --port flag sets the Service port to 80, and --target-port sets the container port to 8080, correctly mapping Service port 80 to pod port 8080.

Exam trap

XK0-006 often tests the difference between exposing a deployment vs. a pod, and between ClusterIP/NodePort/LoadBalancer service types — candidates pick 'create service nodeport' or expose a pod, missing that the default type is ClusterIP and that deployments should be exposed for scalability.

How to eliminate wrong answers

Option A is wrong because 'kubectl create service nodeport' creates a NodePort service (exposing the service on each node's IP at a static port), not a ClusterIP service, and it uses the --tcp flag syntax rather than --port/--target-port. Option C is wrong because it exposes a pod named 'web-app' rather than the deployment; while it might work if a pod with that name exists, the question specifies exposing the deployment, and exposing a pod directly bypasses the deployment's replica management and load balancing across pods. Option D is wrong because 'kubectl create service clusterip' creates a ClusterIP service but uses the --tcp=<port>:<targetPort> syntax and does not reference the deployment's selector automatically — it requires manual selector specification and does not tie to the deployment by name.

25
MCQeasy

A Docker container is running in the background. Which command allows the administrator to execute an interactive bash shell inside the running container named 'webapp'?

A.docker start -i webapp
B.docker run -it webapp bash
C.docker exec -it webapp bash
D.docker attach webapp
AnswerC

docker exec runs a new process inside an already running container; -it allocates an interactive TTY and keeps stdin open, and bash specifies the shell. This satisfies the requirement without restarting or attaching to the main process.

Why this answer

docker exec -it runs an interactive command in a running container. The other commands are for different purposes.

26
MCQhard

An administrator is troubleshooting a Kubernetes deployment that is not receiving traffic. The deployment has one replica and the pod is running. The service is of type ClusterIP. Which command would help verify that the service endpoints are correctly associated with the pod?

A.kubectl describe pod
B.kubectl get pods -o wide
C.kubectl get svc
D.kubectl get endpoints
AnswerD

`kubectl get endpoints` lists each Service's backing pod IPs and ports, directly confirming whether the ClusterIP Service's selector actually matched the running pod. Since the stem's constraint is a ClusterIP Service with no external exposure, endpoint association is the failure point to verify, and this command exposes an empty or mismatched endpoint list immediately.

Why this answer

The 'kubectl get endpoints' command lists the Endpoints object for a service, showing the IP addresses and ports of the pods that back it. If the service selector does not match the pod labels, the endpoints list will be empty, immediately revealing the misconfiguration. This is the fastest way to verify service-to-pod association.

Exam trap

XK0-006 often tests whether candidates know that 'kubectl get svc' shows the selector but not the resolved endpoints, trapping those who assume the service output confirms pod association.

How to eliminate wrong answers

Option A is wrong because 'kubectl describe pod' shows pod details (status, events, containers) but does not show which service endpoints reference the pod. Option B is wrong because 'kubectl get pods -o wide' shows pod IPs and nodes but not the service-to-pod mapping. Option C is wrong because 'kubectl get svc' shows the service's ClusterIP, ports, and selector but not the resolved endpoints — it will not reveal whether the selector matches any pods.

27
MCQeasy

A Linux administrator writes a bash script that needs to exit immediately if any command fails. Which of the following should be included at the beginning of the script?

A.set -x
B.set -u
C.set -e
D.set -o pipefail
AnswerC

The set -e option instructs bash to terminate the script immediately when any command returns a non-zero exit status. Placing it at the top satisfies the requirement that the script halts on first failure rather than continuing with subsequent commands.

Why this answer

set -e (errexit) causes the shell to exit immediately if any command returns a non-zero exit status, which is exactly the requirement. It is the standard way to make bash scripts fail fast rather than continuing after an error.

Exam trap

XK0-006 often tests the difference between set -e (exit on error), set -u (error on unset variable), set -x (trace), and set -o pipefail (pipeline failure propagation) — candidates frequently pick pipefail thinking it alone causes script exit.

How to eliminate wrong answers

Option A is wrong because set -x enables command tracing (prints each command before execution) for debugging, not error handling. Option B is wrong because set -u treats unset variables as errors, which is useful for catching typos but does not exit on command failure. Option D is wrong because set -o pipefail only changes pipeline exit status to reflect the last failing command in the pipe — it does not by itself cause the script to exit on failure (it is often combined with set -e).

28
MCQmedium

A Linux administrator is writing a Bash script that must continue running even if an unset variable is referenced, but must still abort on a failed command. Currently the script has only `#!/bin/bash` at the top. Which line should be added to meet these requirements?

A.set -x
B.set -u
C.set -o pipefail
D.set -e
AnswerD

`set -e` causes the shell to exit immediately when a command returns a non-zero status, satisfying the requirement to abort on failed commands. Because `-u` is not included, referencing an unset variable does not terminate the script, so the script continues running. This combination precisely matches the administrator's stated requirements.

Why this answer

The requirement is to abort on a failed command while still tolerating references to unset variables. `set -e` provides the abort-on-error behavior, and because `-u` is not enabled, unset variables do not trigger termination. Enabling trace output or altering pipeline exit status does not produce the requested failure semantics, and enabling unset-variable errors would do the opposite of what is required.

Exam trap

The trap here is assuming that any `set` option that influences error handling will also make the script exit on a failed command.

29
MCQhard

A Linux administrator is writing a Bash script that processes a list of hostnames stored one per line in /etc/app/hosts.list. The script must read each line into the variable host and run a command against it, and the loop must not consume standard input from the terminal so that interactive commands inside the loop can still read from the keyboard. Which construct satisfies these requirements?

A.for host in $(cat /etc/app/hosts.list); do probe "$host"; done
B.while IFS= read -r host <&3; do probe "$host"; done 3< /etc/app/hosts.list
C.until read host; do probe "$host"; done < /etc/app/hosts.list
D.while read -r host; do probe "$host"; done < /etc/app/hosts.list
AnswerB

This opens the hostname file on file descriptor 3 and reads from it with read <&3, leaving file descriptor 0 untouched. Interactive commands inside probe can therefore still read from the keyboard, and IFS= with -r preserves leading whitespace and backslashes. It is the standard technique for keeping stdin available while looping over a file.

Why this answer

Redirecting the list to an alternate file descriptor and reading with read <&3 keeps standard input attached to the terminal, so interactive commands invoked in the loop body can still prompt the user. Using IFS= read -r also preserves hostname characters verbatim, which the whitespace-splitting for loop and the stdin-consuming while form cannot guarantee.

Exam trap

The trap here is assuming that any while-read loop over a file is equivalent, when the redirection target determines whether stdin remains usable by commands inside the loop.

30
MCQmedium

A DevOps engineer needs to debug a bash script that unexpectedly fails when processing files. Which of the following should be added to the script to print each command before execution?

A.set -v
B.set -e
C.set -x
D.set -u
AnswerC

`set -x` enables the shell's trace mode, printing each command to stderr after expansion but before execution, prefixed with `+`. This satisfies the stem's requirement to display every command as it runs, letting the engineer follow the script's actual execution path and pinpoint where file processing fails.

Why this answer

set -x enables shell tracing, which prints each command (with expanded variables) to stderr prefixed by PS4 (usually '+') before execution. This is exactly what is needed to see what the script is doing as it processes files and where it fails.

Exam trap

XK0-006 often tests the distinction between set -x (trace executed commands) and set -v (echo input lines) — candidates pick -v thinking it shows execution, but only -x shows expanded commands as they run.

How to eliminate wrong answers

Option A is wrong because set -v prints shell input lines as they are read, not after expansion — it shows the raw script text rather than the actual commands being executed with their expanded values. Option B is wrong because set -e causes the script to exit immediately on any command returning non-zero, which is error handling, not debugging output. Option D is wrong because set -u treats unset variables as an error and exits, which helps catch typos but does not print commands before execution.

31
MCQeasy

A Linux administrator wants to ensure a Bash script exits immediately if any command fails. Which directive should be included at the beginning of the script?

A.set -o pipefail
B.set -u
C.set -e
D.set -x
AnswerC

set -e makes the shell terminate immediately when any command returns a non-zero exit status, satisfying the requirement to stop on failure. Without it, Bash continues executing subsequent commands by default, masking the error and allowing the script to run on with corrupted state.

Why this answer

The `set -e` directive (equivalent to `set -o errexit`) causes the shell to exit immediately when any command returns a non-zero exit status, unless that command is part of a condition (if/while/until) or followed by `||`. This is the standard way to make a Bash script fail fast on the first error. Placing it near the top of the script ensures subsequent commands are not executed after a failure.

Exam trap

XK0-006 often tests the difference between `set -e`, `set -u`, `set -x`, and `set -o pipefail` — candidates confuse the fail-fast directive with pipefail or with debugging flags, especially because all four are commonly written together as `set -euxo pipefail`.

How to eliminate wrong answers

Option A is wrong because `set -o pipefail` only changes the exit status of a pipeline to reflect the last failing command in the pipe; it does not by itself cause the script to exit on failure. Option B is wrong because `set -u` treats unset variables as an error, which is about variable expansion, not command failure handling. Option D is wrong because `set -x` enables trace output of commands as they execute, which is a debugging aid, not an error-handling directive.

32
MCQmedium

A configuration-management script must take a YAML inventory file and convert it into JSON so a downstream API can consume it, preserving all nested structure. Which command accomplishes this most directly?

A.awk -F': ' '{print $2}' inventory.yaml
B.grep -E '^[a-zA-Z]+:' inventory.yaml
C.yq -o=json '.' inventory.yaml
D.sed 's/:/=/g' inventory.yaml
AnswerC

The yq utility parses YAML natively and its -o=json output flag re-serializes the whole document as JSON, keeping nested maps and lists intact. The identity filter '.' selects the entire document, so this single command produces valid JSON that the API can consume without any intermediate text manipulation.

Why this answer

Structured conversion requires a tool that understands YAML syntax, and yq does exactly that by parsing the document and emitting JSON when given the -o=json flag. Text utilities such as sed, grep, and awk operate line by line and cannot reconstruct nested maps and sequences, so they inevitably corrupt the data the API expects.

Exam trap

The trap here is assuming a general-purpose text tool can convert between structured data formats when only a format-aware parser preserves nesting.

33
MCQmedium

A Linux administrator is writing a Bash script that must run a cleanup routine when the script exits, whether it exits normally or is interrupted by a signal. The script defines a function named cleanup. Which command should the administrator use to ensure cleanup runs on exit?

A.setsid cleanup &
B.trap 'cleanup' EXIT
C.at now + 1 minute <<< cleanup
D.trap 'cleanup' SIGKILL
AnswerB

The trap builtin with the EXIT pseudo-signal runs the specified command when the shell exits, regardless of whether the exit is normal or caused by a signal such as SIGINT. This matches the requirement to run cleanup unconditionally at script termination, and the single quotes defer expansion of cleanup until the trap fires.

Why this answer

The trap builtin is the standard Bash mechanism for running commands in response to signals or shell events. Using the EXIT pseudo-signal makes the handler run on any script termination, including normal completion and receipt of catchable signals, which is exactly what the administrator needs for a guaranteed cleanup routine.

Exam trap

The trap here is assuming that any signal name works with trap, when SIGKILL and SIGSTOP are uncatchable and can never trigger a handler.

34
MCQmedium

A DevOps engineer is writing a Bash script that checks if a file exists and is readable. Which test condition should be used inside an if statement?

A.[[ -e file ]]
B.[[ -f file ]]
C.[[ -s file ]]
D.[[ -r file ]]
AnswerD

Correct. -r returns true if the file exists and has read permission.

Why this answer

The -e test checks if a file exists, and -r checks if it is readable. Using -f also checks for a regular file, but the question requires existence and readability, so combining -e and -r is correct. However, the options include -f and -r, but -f alone does not check readability.

The correct combination is -e and -r, but since that is not an option, the best answer is -r because it implies existence? Actually, -r returns true only if the file exists and is readable. So -r alone satisfies both conditions.

35
Multi-Selectmedium

A Linux administrator is writing a Bash script that uses a function. Which two statements about Bash functions are correct? (Choose TWO.)

Select 2 answers
A.Functions are called by their name without parentheses.
B.Functions can return a value using the return statement.
C.Function definitions must be placed at the beginning of the script.
D.Functions cannot accept arguments.
E.Functions can be called before they are defined.
AnswersA, B

Functions are invoked by name; parentheses are used only in definition.

Why this answer

Bash functions must be defined before use and are called by name without parentheses.

36
MCQmedium

In a Kubernetes cluster, a developer needs to create a Deployment that runs three replicas of a container image 'myapp:1.0' and exposes port 8080. Which YAML snippet correctly defines this Deployment?

A.apiVersion: v1 kind: Pod metadata: name: myapp spec: replicas: 3 containers: - name: myapp image: myapp:1.0 ports: - containerPort: 8080
B.apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 3 selector: app: myapp template: containers: - name: myapp image: myapp:1.0 ports: - containerPort: 8080
C.apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp:1.0 ports: - containerPort: 8080
D.apiVersion: v1 kind: Deployment metadata: name: myapp spec: replicas: 3 template: spec: containers: - name: myapp image: myapp:1.0 ports: - containerPort: 8080
AnswerC

Correct. Includes required apiVersion, selector, and template with labels.

Why this answer

A Deployment YAML must have apiVersion, kind, metadata, spec with replicas and template containing container spec with image and ports.

37
MCQeasy

A Kubernetes YAML manifest defines a Deployment. Which field specifies the number of pod replicas to run?

A.metadata.replicas
B.spec.template.replicas
C.spec.containers.replicas
D.spec.replicas
AnswerD

The replicas field sits under the Deployment's spec, declaring the desired pod count that the ReplicaSet controller continuously reconciles. Setting spec.replicas to the required number satisfies the stem's demand for specifying how many identical pods run concurrently.

Why this answer

In a Deployment spec, the 'replicas' field sets the desired number of pod instances.

38
MCQeasy

In a Bash script, what is the purpose of the shebang '#!/bin/bash'?

A.It specifies the path to the Bash executable that should run the script.
B.It defines a variable for the Bash version.
C.It sets the script's permissions to executable.
D.It enables debug mode for the script.
AnswerA

The shebang's first line tells the kernel which interpreter binary executes the file, so `#!/bin/bash` names the absolute path to Bash. This satisfies the stem's requirement by ensuring the script runs under Bash rather than the invoking shell, regardless of the user's default login shell.

Why this answer

The shebang tells the system which interpreter to use to execute the script.

39
MCQmedium

A Linux administrator needs to run a Docker container in detached mode with port mapping from host port 8080 to container port 80, and mount a host directory /data to /app/data inside the container. Which command achieves this?

A.docker run -d -p 8080:80 -v /data:/app/data --name webapp nginx
B.docker run -it -p 8080:80 -v /data:/app/data --name webapp nginx
C.docker run -d -P -v /data:/app/data --name webapp nginx
D.docker start -d -p 8080:80 -v /data:/app/data webapp
AnswerA

The -d flag detaches the container, -p 8080:80 maps host port 8080 to container port 80, and -v /data:/app/data bind-mounts the host directory. Together these satisfy every stated constraint in a single command, using the nginx image.

Why this answer

Option A is correct because it uses `docker run -d` to start the container in detached mode (background), `-p 8080:80` to map host port 8080 to container port 80, and `-v /data:/app/data` to bind-mount the host directory `/data` to the container path `/app/data`. The `--name webapp` assigns a friendly name, and `nginx` specifies the image. This combination exactly matches all requirements.

Exam trap

The trap here is confusing `-p` (specific port mapping) with `-P` (publish all exposed ports to random host ports), and mixing up `docker run` with `docker start`; candidates may also overlook that `-it` is not detached mode.

How to eliminate wrong answers

Option B is wrong because it uses `-it` (interactive with TTY) instead of `-d`, which runs the container in the foreground and attaches the terminal, not detached mode. Option C is wrong because it uses `-P` (uppercase) which publishes all exposed ports to random host ports, not the specific mapping 8080:80; also it lacks the explicit `-p 8080:80` mapping. Option D is wrong because `docker start` is used to start an existing stopped container and does not accept `-p` or `-v` flags; those options are only valid with `docker run` at container creation time.

40
MCQeasy

In a Bash script, what is the correct way to check if a file named '/etc/passwd' exists and is a regular file?

A.if [ -r /etc/passwd ]
B.if [ -e /etc/passwd ]
C.if [ -s /etc/passwd ]
D.if [ -f /etc/passwd ]
AnswerD

The -f unary test operator returns true when the path exists and is a regular file, excluding directories and other special types. Used inside [ ], it satisfies the requirement to verify that /etc/passwd exists as a regular file.

Why this answer

The `-f` test operator in Bash returns true only if the path exists AND is a regular file (not a directory, device, or symlink to a non-regular file). This exactly matches the requirement to check that /etc/passwd exists and is a regular file.

Exam trap

The trap is assuming `-e` (exists) is sufficient when the question specifically asks for a regular file — candidates often pick `-e` because it 'checks existence'.

How to eliminate wrong answers

Option A is wrong because `-r` tests readability, not file type — a directory or device could be readable. Option B is wrong because `-e` only tests existence and returns true for directories, sockets, and devices. Option C is wrong because `-s` tests that the file exists and has a size greater than zero, which does not verify it is a regular file.

41
MCQhard

A Linux administrator is writing a Bash script that processes a list of filenames stored one per line in a file. Some filenames contain spaces. The administrator wants the loop to treat each full line as a single item without word-splitting, and also wants to strip the trailing newline from each item. Which construct accomplishes this?

A.while read line; do process "$line"; done < filelist
B.while IFS= read -r line; do process $line; done < filelist
C.while IFS= read -r line; do process "$line"; done < filelist
D.for line in $(cat filelist); do process "$line"; done
AnswerC

Setting IFS= for the read command disables trimming of leading and trailing whitespace, and the -r flag prevents backslashes from being interpreted as escapes. read consumes one line at a time and strips the terminating newline, so filenames with embedded spaces stay intact and are passed quoted to process. This is the canonical safe line-reading loop.

Why this answer

Reading lines safely in Bash requires neutralizing both whitespace trimming and escape processing. IFS= preserves the line exactly, and -r stops backslashes from acting as escapes. Quoting the variable at every use prevents a second round of word splitting.

Only the construct that combines all three elements keeps filenames with spaces or special characters as single, unmodified arguments.

Exam trap

The trap here is fixing the read command but forgetting to quote the variable at the point of use, which re-splits the line anyway.

42
MCQeasy

A Linux administrator is writing a Bash script that accepts a filename as its first argument. The script should print an error and exit if the argument is missing. Which construct should the administrator use to reference the first positional parameter and test whether it is empty?

A.$0 with the -z test, as in [ -z "$0" ]
B.$1 with the -z test, as in [ -z "$1" ]
C.$# with the -z test, as in [ -z "$#" ]
D.$@ with the -z test, as in [ -z "$@" ]
AnswerB

The positional parameter $1 holds the first argument passed to the script. Wrapping it in double quotes preserves empty or whitespace-containing values, and the -z test returns true when the string length is zero, which correctly detects a missing argument and allows the script to print an error and exit.

Why this answer

The first positional parameter is referenced as $1, and quoting it preserves its value even when empty. The -z test evaluates to true for a zero-length string, so checking [ -z "$1" ] reliably detects a missing filename argument and lets the script print an error and exit before proceeding.

Exam trap

The trap here is mixing up the positional parameter variables, since $0 is the script name and $# is the argument count rather than the first argument.

43
MCQmedium

A developer wants to run a containerized application using Podman in a rootless environment. Which of the following is a key difference between Podman and Docker that the developer should be aware of?

A.Podman can run containers without a daemon
B.Podman requires a daemon to manage containers
C.Podman only supports rootful containers
D.Podman uses a different CLI syntax than Docker
AnswerA

Podman runs containers directly as child processes without a long-running daemon, which suits rootless operation because no privileged background service is needed. Docker relies on the dockerd daemon, typically requiring root or elevated privileges for container management.

Why this answer

Podman supports rootless containers natively without requiring a daemon, unlike Docker which traditionally requires a daemon (dockerd) running as root.

44
MCQmedium

A Linux administrator needs to schedule a maintenance script to run every Monday at 03:15 on a systemd-based server. The script must persist across reboots and must not depend on a user being logged in. Which of the following is the BEST approach?

A.Add the entry to /etc/crontab using the root user field, then run systemctl restart crond.
B.Place a script in /etc/profile.d/ that invokes the maintenance command, ensuring it runs for every user session.
C.Create a systemd timer unit with OnCalendar=Mon 03:15:00 and a matching service unit, then enable the timer with systemctl enable --now.
D.Create an at job with at 03:15 Mon and save it with atq so it repeats weekly.
AnswerC

A systemd timer paired with a service unit is the native scheduling mechanism on systemd-based distributions. The OnCalendar directive accepts calendar expressions such as Mon 03:15:00, and enabling the timer with systemctl enable --now ensures it starts immediately and persists across reboots without requiring an interactive login session.

Why this answer

Systemd timers are the modern, native scheduling mechanism on systemd-based Linux distributions. Pairing a timer unit that defines OnCalendar=Mon 03:15:00 with a service unit that runs the script, then enabling the timer, satisfies the requirement for a recurring, reboot-persistent job that runs without any logged-in user. This approach is more robust than legacy cron or one-shot at jobs.

Exam trap

The trap here is assuming that cron is always available and preferred on systemd-based systems, when native timer units are the more reliable and integrated choice.

45
MCQhard

A Linux administrator needs to schedule a script to run every Monday at 3:00 AM. The script is located at /opt/scripts/weekly_report.sh. Which entry should be added to the crontab to accomplish this?

A.0 3 * * 1 /opt/scripts/weekly_report.sh
B.3 0 * * 1 /opt/scripts/weekly_report.sh
C.0 3 1 * * /opt/scripts/weekly_report.sh
D.0 3 * * 0 /opt/scripts/weekly_report.sh
AnswerA

The cron format is minute hour day-of-month month day-of-week command. '0 3 * * 1' means minute 0, hour 3 (3:00 AM), any day of month, any month, and day-of-week 1 (Monday). This exactly matches the requirement to run every Monday at 3:00 AM. The script path is absolute, which is best practice for cron jobs.

Why this answer

Cron entries consist of five time fields followed by the command. The correct sequence for Monday at 3:00 AM is minute 0, hour 3, any day of month, any month, and day-of-week 1. This ensures the script runs weekly on Monday at the specified time.

Other options misplace fields or use incorrect day-of-week values, leading to unintended schedules.

Exam trap

The trap here is confusing the day-of-week numbering, where 0 is Sunday and 1 is Monday, or swapping the minute and hour fields.

46
MCQhard

A Linux administrator needs to schedule a recurring backup script to run every Monday at 02:30 using the system-wide cron facility on a systemd-based distribution. Which entry correctly achieves this when placed in /etc/cron.d/backup?

A.30 2 * * 1 root /usr/local/bin/backup.sh
B.30 2 1 * * root /usr/local/bin/backup.sh
C.2 30 * * 1 root /usr/local/bin/backup.sh
D.30 2 * * 1 /usr/local/bin/backup.sh
AnswerA

Files in /etc/cron.d use the extended format that includes a user field between the schedule and the command, so this entry runs the script as root at 02:30 every Monday. The five time fields map to minute, hour, day of month, month, and day of week, satisfying the requirement precisely.

Why this answer

System-wide cron files placed in /etc/cron.d require six fields: minute, hour, day of month, month, day of week, and a user, followed by the command. The correct entry uses minute 30, hour 2, wildcards for day of month and month, day of week 1 for Monday, and root as the executing user, producing a weekly Monday 02:30 run.

Exam trap

The trap here is forgetting that /etc/cron.d entries need an embedded user field, unlike personal crontabs that omit it.

47
MCQhard

In a Bash script, the administrator wants to capture the output of a command into a variable. Which syntax should be used?

A.$VAR
B.$((command))
C.`command`
D.$(command)
AnswerD

Command substitution with $(command) runs the command in a subshell and substitutes its standard output, which is then assigned to the variable. Backticks achieve the same but nest poorly; $(...) is the modern, preferred syntax.

Why this answer

Command substitution can be done with $(command) or backticks `command`. The latter is deprecated. $(( )) is for arithmetic expansion. $VAR is for variable expansion.

48
Multi-Selectmedium

A Linux administrator is automating container builds and needs to reduce image size and ensure reproducibility. Which TWO practices should be applied when writing the Dockerfile? (Choose two.)

Select 2 answers
A.Pin base images and package versions to specific tags or digests
B.Add a separate RUN apt-get update in every RUN instruction that installs packages
C.Copy the entire build context into the image with COPY . /app before installing dependencies
D.Combine related RUN commands and clean package caches in the same layer
E.Use the `latest` tag for all base images to always receive security updates
AnswersA, D

Referencing a mutable tag such as `latest` means a rebuild can pull a different base image, producing non-reproducible results. Pinning to an explicit version tag or image digest guarantees the same inputs are used across builds, which is the core requirement for reproducible container images in automated pipelines.

Why this answer

Image size and reproducibility are improved by minimizing layers and pinning inputs. Combining install and cleanup in one RUN prevents deleted cache files from persisting in earlier layers, and pinning base images and package versions ensures identical builds. Using mutable tags, splitting update from install, or copying the full context early all work against these goals.

Exam trap

The trap here is believing that deleting files in a later RUN removes them from the image, when earlier layers still contain them.

49
MCQeasy

In a Bash script, what is the difference between single quotes and double quotes?

A.Both behave the same.
B.Single quotes allow variable expansion; double quotes do not.
C.Double quotes prevent all substitutions; single quotes allow command substitution.
D.Single quotes prevent variable expansion; double quotes allow it.
AnswerD

Within single quotes, Bash treats every character literally, so $VAR stays unexpanded; double quotes permit parameter and command substitution while still suppressing word splitting and globbing. This satisfies the stem's request for the precise difference in expansion behaviour between the two quoting styles.

Why this answer

Single quotes preserve the literal value of each character, while double quotes allow variable expansion and command substitution.

50
Multi-Selecthard

A DevOps engineer is creating a Dockerfile for a Node.js application. Which THREE of the following instructions are valid and commonly used in a Dockerfile? (Choose THREE.)

Select 3 answers
A.EXECUTE node app.js
B.COPY . /app
C.RUN npm install
D.INSTALL package.json
E.FROM node:14
AnswersB, C, E

COPY transfers files from the build context into the image, here placing the project's source at /app. It satisfies the need to get application code into the image before running npm install and CMD. Unlike ADD, COPY performs no URL fetching or archive extraction, keeping the build predictable.

Why this answer

Option B, COPY . /app, is correct because COPY is a valid Dockerfile instruction that copies files from the build context into the image filesystem, here placing the application source into /app. Option C, RUN npm install, is correct because RUN executes commands during the image build, and npm install is the standard way to install Node.js dependencies inside the image. Option E, FROM node:14, is correct because FROM is the required first instruction in a Dockerfile that sets the base image, and node:14 is a valid Node.js base image tag.

Option A, EXECUTE node app.js, is not a Dockerfile instruction; the correct instruction for starting the container process is CMD or ENTRYPOINT. Option D, INSTALL package.json, is also not a Dockerfile instruction; dependency installation is done with RUN, and package.json is typically copied with COPY.

Exam trap

XK0-006 often tests recognition of valid Dockerfile instructions versus plausible-sounding but nonexistent ones (EXECUTE, INSTALL), so candidates must know the canonical instruction set (FROM, RUN, COPY, ADD, CMD, ENTRYPOINT, EXPOSE, WORKDIR, ENV, etc.).

51
MCQmedium

A Docker container needs to persistently store data that should survive container removal and be accessible by other containers. Which storage method should be used?

A.Volume
B.Bind mount
C.Container layer
D.tmpfs mount
AnswerA

Docker volumes are stored outside the container's writable layer, in a managed host directory, so their data persists after the container is removed and can be mounted by multiple containers simultaneously, satisfying both persistence and cross-container sharing.

Why this answer

Docker volumes are managed by Docker itself and stored in a dedicated area of the host filesystem (typically /var/lib/docker/volumes on Linux), which is outside the container's writable layer. Because they are independent of the container lifecycle, data in a volume persists even after the container is removed, and the same volume can be mounted into multiple containers simultaneously, enabling data sharing. This makes volumes the recommended mechanism for persistent, shareable container data.

Exam trap

The trap here is confusing bind mounts with volumes: both persist data, but only volumes are Docker-managed, portable, and shareable across containers, which is what the question's 'accessible by other containers' requirement demands.

How to eliminate wrong answers

Option B is wrong because bind mounts tie the container to a specific host path, which is less portable and not managed by Docker, so they are not the recommended method for portable persistent storage. Option C is wrong because the container layer is ephemeral — it is destroyed when the container is removed, so data written there does not survive container deletion. Option D is wrong because tmpfs mounts store data in host memory only and are removed when the container stops, providing no persistence at all.

52
MCQhard

An automation engineer uses Ansible to configure a fleet of Linux servers. A playbook task installs a package and then starts a service, but the service fails to start because the package installs a configuration file only on the first run. The engineer wants the handler to notify only when the package actually changes state. Which Ansible construct ensures the service restart handler fires only when the package task reports a change?

A.Set `run_once: true` on the service handler so it executes a single time per play.
B.Use the `notify` directive on the package task referencing a handler that restarts the service.
C.Add `changed_when: true` to the package task to guarantee the handler always runs.
D.Use the `when: ansible_facts.pkg_mgr == 'apt'` conditional on the handler.
AnswerB

Handlers are only invoked when the notifying task reports `changed`, so binding the restart to the package installation via `notify` ensures the service restarts precisely when the package changes. On subsequent idempotent runs where the package is already present, the task reports `ok` and the handler does not fire, matching the requirement to act only on real state changes.

Why this answer

Ansible handlers run only when notified by a task that reports `changed`, which is exactly the behavior needed to restart a service only when its package is actually installed or upgraded. The `notify` directive wires the package task to the handler, so idempotent runs that leave the package untouched do not trigger a restart, preventing unnecessary service interruptions across the managed fleet.

Exam trap

The trap here is thinking a handler must be forced to run with `changed_when` rather than simply being notified by a genuinely changed task.

53
MCQhard

A Linux administrator needs to automate the deployment of a Kubernetes application from a manifest file and verify that the rollout completes successfully within a script. Which pair of actions should the script perform to apply the manifest and block until the Deployment's rollout finishes?

A.kubectl apply -f deploy.yaml followed by kubectl rollout status deployment/myapp
B.kubectl apply -f deploy.yaml followed by kubectl describe deployment/myapp
C.kubectl replace -f deploy.yaml followed by kubectl logs deployment/myapp
D.kubectl create -f deploy.yaml followed by kubectl get pods -w
AnswerA

Applying the manifest creates or updates the resources, and kubectl rollout status blocks until the Deployment's rollout completes or fails, returning a non-zero exit code on failure. This combination lets the script confirm success programmatically before proceeding to the next step in the automation workflow.

Why this answer

Idempotent automation uses kubectl apply to create or update resources from a manifest, then kubectl rollout status to block until the Deployment rollout completes, which exits non-zero on failure. Alternatives like get with watch or describe do not provide a deterministic completion signal, and create or replace are not idempotent for repeated script runs.

Exam trap

The trap here is assuming that watching pods or describing a Deployment confirms rollout success, when neither provides a reliable blocking exit status for automation.

54
MCQmedium

A team uses Ansible for configuration management. They want to ensure a service is running on all managed nodes. Which Ansible module should be used in the playbook?

A.systemd
B.service
C.command
D.shell
AnswerB

The `service` module manages service state on managed nodes, directly satisfying the requirement to ensure a service is running across all hosts. It supports `state: started` and `enabled`, unlike `command` or `shell`, which execute arbitrary commands without idempotent service-state handling. This makes it the appropriate declarative choice for the playbook.

Why this answer

The Ansible service module is the generic, cross-platform module for managing services (started, stopped, enabled, restarted) and works across systemd, SysVinit, Upstart, and other init systems. It is the correct choice when the playbook must ensure a service is running on all managed nodes regardless of the underlying init system. Using service with state: started and enabled: yes is the idiomatic way to guarantee a service is running and persists across reboots.

Exam trap

The trap is assuming systemd is always the right module because it is modern — but the question says 'all managed nodes,' implying heterogeneity, where the generic service module is safer.

How to eliminate wrong answers

Option A is wrong because the systemd module is specific to systems using systemd as the init system; it will fail on hosts using SysVinit or Upstart, so it is not the best choice for 'all managed nodes' in a heterogeneous environment. Option C is wrong because the command module runs arbitrary commands and is not idempotent for service management — it does not understand service state and would report changed every run. Option D is wrong because the shell module runs commands through a shell and, like command, lacks idempotent service-state management and is intended for shell-specific operations, not service control.

55
MCQmedium

In a bash script, a developer needs to parse command-line options such as -f filename and -v (verbose). Which built-in command is best suited for this task?

A.getopt
B.getopts
C.case
D.shift
AnswerB

getopts is a bash built-in that parses short options with arguments, such as -f filename, and sets OPTARG and OPTIND automatically. It handles the -v flag and option-argument pairing natively, unlike manual shifting or external parsers.

Why this answer

getopts is a bash built-in for parsing command-line options. It handles short options and requires option arguments.

56
MCQhard

A Linux administrator is troubleshooting a Bash script that must parse each line of a file named `servers.txt` and process fields separated by colons. The script currently uses `for line in $(cat servers.txt)` and breaks on lines containing spaces. Which construct should replace the loop to correctly iterate over lines while preserving whitespace?

A.for line in $(< servers.txt); do ... done
B.while IFS= read -r line; do ... done < servers.txt
C.cat servers.txt | while read line; do ... done
D.while read -r line < servers.txt; do ... done
AnswerB

`IFS= read -r line` reads a full line without word splitting or backslash interpretation, and redirecting the file into the loop prevents the subshell problem that occurs when piping. This preserves spaces and special characters within each line. It is the standard, reliable pattern for line-by-line processing in Bash scripts.

Why this answer

Reading lines reliably requires disabling word splitting and backslash processing with `IFS= read -r line`, and attaching the input redirection to the `while` loop so the loop does not run in a subshell. Piping into the loop loses variable state, command substitution splits on whitespace, and placing the redirection on the `read` command reopens the file on each iteration instead of advancing through it.

Exam trap

The trap here is piping into `while read`, which appears to work for simple output but silently loses variable changes made inside the loop.

57
Multi-Selectmedium

A Linux administrator is automating container lifecycle tasks with a script and needs to ensure a specific container, named webapp, is stopped cleanly and removed, while also removing its anonymous volumes. Which TWO docker commands should be used to accomplish this? (Choose two.)

Select 2 answers
A.docker volume prune -a
B.docker rmi webapp
C.docker rm -v webapp
D.docker stop webapp
E.docker kill webapp
AnswersC, D

Removing the stopped container with the -v flag also deletes any anonymous volumes associated with it, satisfying the requirement to clean up volumes. The container must be stopped first, which the other selected command handles, so this completes the lifecycle cleanup for the webapp container.

Why this answer

A clean container teardown involves stopping the container so its main process receives SIGTERM and can exit gracefully, then removing the container with the -v flag to delete its anonymous volumes. Using SIGKILL or broad volume pruning bypasses graceful shutdown or affects unrelated resources, and removing an image does not address the container or its volumes.

Exam trap

The trap here is reaching for docker kill or global volume pruning, which act forcefully or system-wide instead of cleanly targeting the named container and only its volumes.

58
MCQhard

A Linux administrator writes a Bash script that processes a list of hostnames read from a file and must continue processing remaining hosts even if an SSH command to one host fails. The script currently uses set -e and exits on the first failure. Which change allows the loop to keep running while still exiting on other unhandled errors?

A.Append || true to the SSH command inside the loop.
B.Wrap the SSH command in a subshell with parentheses.
C.Replace set -e with set +e globally.
D.Redirect stderr to /dev/null on the SSH command.
AnswerA

Under set -e, a command that is part of an OR list such as cmd || true is exempt from triggering exit, because the shell only aborts when the last command in the list returns non-zero. Appending || true lets the SSH failure be tolerated for that iteration while errexit still guards the rest of the script, which is precisely the requested behavior.

Why this answer

Bash's errexit option does not trigger on commands whose failure is consumed by a logical construct. Because the shell checks the exit status of the entire AND-OR list, appending || true to the SSH invocation means the list returns zero even when SSH fails, so the loop continues. Other commands in the script remain protected by set -e, preserving the desired fail-fast behavior elsewhere.

Exam trap

The trap here is assuming set -e applies uniformly, when commands inside conditionals, AND-OR lists, or negations are exempt from triggering the exit.

59
MCQeasy

A Linux administrator is writing a bash script that must exit immediately if any command fails. Which of the following should be included at the beginning of the script?

A.set -e
B.set -o pipefail
C.set -u
D.set -x
AnswerA

set -e makes bash terminate the script immediately when any command returns a non-zero exit status, matching the requirement to abort on failure. Placed at the top, it governs all subsequent commands in the script.

Why this answer

`set -e` (errexit) causes the shell to exit immediately when any command returns a non-zero exit status, which is exactly the requirement for a script that must stop on the first failure. It is the standard idiom placed at the top of defensive bash scripts.

Exam trap

XK0-006 often tests the confusion between `set -e` (exit on error), `set -u` (unset variable error), `set -x` (trace), and `pipefail` (pipeline exit status), so candidates must match the exact behavior described.

How to eliminate wrong answers

Option B is wrong because `set -o pipefail` only changes the exit status of a pipeline to reflect the last failing command in the pipe — it does not by itself cause the script to exit on failure. Option C is wrong because `set -u` (nounset) causes an error when an unset variable is referenced; it does not handle command failures. Option D is wrong because `set -x` enables trace output of each command for debugging, not fail-fast behavior.

60
MCQmedium

A Bash script contains the following function: ```bash myfunc() { local result="$(( $1 + $2 ))" echo "$result" } ``` If the script calls `myfunc 5 10`, what is the output?

A.510
B.5+10
C.the function returns nothing
D.15
AnswerD

The function adds its two positional arguments, 5 and 10, storing the arithmetic result in a local variable, then echoes it. Bash arithmetic expansion evaluates the sum to 15, which is printed as the output.

Why this answer

The function uses arithmetic expansion $(( $1 + $2 )) with positional parameters 5 and 10, which evaluates to 15. The result is stored in a local variable and echoed to stdout, so calling myfunc 5 10 prints 15.

Exam trap

The trap is confusing a function's exit status (return) with its stdout output (echo), leading candidates to select 'the function returns nothing' even though echo clearly produces visible output.

How to eliminate wrong answers

Option A is wrong because 510 would result from string concatenation (e.g., echo "$1$2"), but the arithmetic expansion $(( )) forces numeric addition. Option B is wrong because 5+10 would only appear if the expression were echoed literally without arithmetic evaluation, which is not the case here. Option C is wrong because the function explicitly echoes $result, so it does produce output; the misconception likely stems from confusing return values with stdout output.

61
Multi-Selectmedium

In a bash script, a function is defined to calculate a value. Which TWO of the following are valid ways to return a value from the function to the caller? (Select TWO).

Select 2 answers
A.exit 42
B.echo 42
C.return 42
D.return 'value'
E.print 42
AnswersB, C

Prints 42 to stdout; caller can capture with result=$(function).

Why this answer

The return statement sets the exit status (0-255). echo outputs to stdout which can be captured via command substitution. Functions cannot return arbitrary integers directly via return if >255.

62
MCQeasy

A Linux administrator needs a scheduled task to run a backup script at 02:30 every day of the week. The system uses cron, and the administrator is editing the crontab for the `backup` user. Which crontab entry accomplishes this?

A.30 2 * * * /usr/local/bin/backup.sh
B.2 30 * * * /usr/local/bin/backup.sh
C.30 2 1 * * /usr/local/bin/backup.sh
D.* 2 * * * /usr/local/bin/backup.sh
AnswerA

The five fields of a crontab entry are minute, hour, day of month, month, and day of week. `30 2 * * *` means minute 30 of hour 2 (02:30) on every day of every month and every day of the week. This matches the requirement to run the backup script daily at 02:30.

Why this answer

A standard crontab line places minute first, then hour, day-of-month, month, and day-of-week. The requested 02:30 daily schedule requires minute 30 and hour 2 with asterisks in the remaining fields. Transposing the time fields, restricting the day of month, or leaving the minute as a wildcard all produce schedules that do not run the backup once daily at the intended time.

Exam trap

The trap here is reversing the minute and hour fields, since the larger-looking number is often mistaken for the hour.

63
Multi-Selectmedium

An administrator is creating an Ansible playbook to configure multiple web servers. Which of the following are valid ways to define variables for different groups of hosts? (Choose TWO.)

Select 2 answers
A.In a group_vars directory
B.In the inventory file using :vars
C.In a host_vars directory
D.In the playbook itself using vars_files
E.In the roles directory
AnswersA, B

Variables placed in a group_vars directory apply to all hosts in the group.

Why this answer

In Ansible, group variables can be defined in a group_vars directory (A) or directly in the inventory file using the :vars suffix, such as [webservers:vars] (B). The host_vars directory (C) is used for variables specific to individual hosts, not for groups of hosts. Since the question asks for two valid ways to define variables for groups, the correct answers are A and B.

64
MCQhard

A Linux administrator is using Git to manage a configuration repository. They need to undo a commit that has already been pushed to a shared remote repository, without rewriting history. Which command should they use?

A.git rebase -i <commit>
B.git reset --hard <commit>
C.git commit --amend
D.git revert <commit>
AnswerD

`git revert` creates a new commit that undoes the changes introduced by the specified commit. This is safe for shared repositories because it does not alter existing history; it adds a new commit that reverses the changes. It is the recommended way to undo changes that have been pushed, as it preserves the commit history for all collaborators.

Why this answer

To undo a commit that has already been pushed without rewriting history, `git revert` is the correct choice. It creates a new commit that reverses the changes, preserving the original commit in the history. This is safe for collaboration because it does not require force pushing.

Other commands like `reset`, `commit --amend`, or `rebase` rewrite history and should be avoided in shared repositories.

Exam trap

The trap here is thinking that any undo operation requires rewriting history, but `git revert` specifically adds a new commit to undo changes without altering past commits.

65
Multi-Selectmedium

In an Ansible playbook, which THREE of the following are valid modules for managing files and packages? (Select THREE).

Select 3 answers
A.get_url
B.copy
C.apt
D.file
E.command
AnswersB, C, D

Copies files to remote hosts.

Why this answer

(copy) is correct because the copy module is a dedicated Ansible module for copying files from the local control node to remote hosts, supporting attributes like owner, permissions, and content. It is the standard idempotent way to manage file distribution in playbooks.

Exam trap

CompTIA Linux+ often tests the distinction between modules that manage state (copy, file, apt) versus modules that execute commands (command) or retrieve remote content (get_url), trapping candidates who think any module that touches a file is a 'file management' module.

66
MCQhard

A Bash script uses getopts to parse command-line options. The script is invoked as: ./script -a -b value. Which getopts string should be used to correctly parse -a (no argument) and -b (requires an argument)?

A."ab:"
B.":ab"
C."ab"
D."a:b"
AnswerA

The trailing colon after b declares that -b consumes an argument, while the bare a marks -a as a flag taking none. This matches the invocation ./script -a -b value, where getopts assigns value to OPTARG for -b and leaves -a argument-free.

Why this answer

In getopts, a colon after a letter indicates that the option requires an argument. The string 'ab:' means -a takes no argument and -b requires an argument. This matches the invocation './script -a -b value'.

Exam trap

XK0-006 often tests the meaning of colons in getopts strings; candidates may reverse the requirement, thinking a colon means no argument, or forget that the colon must follow the option letter.

How to eliminate wrong answers

Option B is wrong because ':ab' means -a requires an argument and -b takes no argument, which is the opposite of what is needed. Option C is wrong because 'ab' means both -a and -b take no arguments, so -b would not consume 'value'. Option D is wrong because 'a:b' means -a requires an argument and -b takes no argument, again the opposite.

67
MCQeasy

A Linux administrator writes a Bash script and includes the line `#!/bin/bash` at the top. What is the purpose of this line?

A.It sets the script to run in the background.
B.It enables debugging mode.
C.It specifies the interpreter to execute the script.
D.It defines a variable for the script.
AnswerC

The shebang instructs the kernel to launch the named program, here `/bin/bash`, to interpret the script's contents when executed directly. This satisfies the stem's requirement that the line defines which interpreter runs the file, rather than the current shell or a compiled binary.

Why this answer

The `#!/bin/bash` line is a shebang that tells the operating system which interpreter to use when executing the script. When the script is run as an executable, the kernel reads this line and invokes `/bin/bash` to process the file.

Exam trap

XK0-006 often tests whether candidates confuse the shebang with runtime options like `set -x` or with shell invocation flags, so they must recognize it purely as interpreter selection.

How to eliminate wrong answers

Option A is wrong because background execution is controlled by appending `&` when invoking the script, not by the shebang line. Option B is wrong because debugging mode is enabled with `set -x` or by running `bash -x script.sh`, not by the shebang. Option D is wrong because variable definitions use `name=value` syntax; the shebang has no variable-assignment role.

68
Multi-Selectmedium

An administrator is building a container image and needs to reduce its final size while keeping the build reproducible. Which TWO practices improve image efficiency and build reliability? (Choose two.)

Select 2 answers
A.Combine related RUN instructions and clean package caches within the same layer.
B.Add a .dockerignore file that excludes the local .git directory and build artifacts.
C.Use multiple FROM instructions to layer several base images into one final image.
D.Set the ENV HOME variable to a writable path so package managers cache downloads there.
E.Pin base image and package versions to specific tags or digests instead of using latest.
AnswersA, E

Each RUN creates a layer, and deleting files in a later layer only masks them, leaving their bytes in the image. Chaining commands with && and removing caches such as /var/lib/apt/lists in the same RUN prevents that bloat. This keeps the final image smaller and the build deterministic, which matches the stated goal.

Why this answer

Image efficiency hinges on layer mechanics: files removed in a later layer still occupy the earlier one, so cleanup must happen in the same RUN that created the mess. Reproducibility hinges on locked inputs, so base images and packages should be referenced by exact version or digest rather than a moving tag. Combining those two disciplines yields smaller, repeatable builds.

Exam trap

The trap here is believing that deleting a package cache in a separate RUN shrinks the image, when the earlier layer still carries those bytes.

69
MCQmedium

A developer is writing a Dockerfile. The application requires a configuration file that should be copied from the build context and the container should expose port 8080. Which combination of Dockerfile instructions is correct?

A.COPY config.txt /app/ and EXPOSE 8080
B.ADD config.txt /app/ and WORKDIR 8080
C.ADD config.txt /app/ and RUN expose 8080
D.COPY config.txt /app/ and CMD 8080
AnswerA

COPY transfers config.txt from the build context into the image at /app/, satisfying the file requirement, while EXPOSE 8080 documents the port the container listens on at runtime. Both instructions match the stem's constraints precisely, unlike ADD, which also handles remote URLs and archives unnecessarily here.

Why this answer

COPY adds files from the build context, and EXPOSE documents the port. Other instructions serve different purposes.

70
Multi-Selectmedium

In a Bash script, which THREE of the following are valid ways to define a function? (Select THREE.)

Select 3 answers
A.function myfunc() { commands; }
B.myfunc = () { commands; }
C.function myfunc { commands; }
D.def myfunc { commands; }
E.myfunc() { commands; }
AnswersA, C, E

Bash accepts the hybrid syntax combining the function keyword with parentheses and braces. The shell parses function myfunc() { commands; } as a valid definition, so this form satisfies the stem's requirement for a legitimate function declaration alongside the other two accepted variants.

Why this answer

Option A, `function myfunc() { commands; }`, is correct because Bash accepts the `function` keyword combined with parentheses, a hybrid syntax that is valid in Bash (though not POSIX sh). Option C, `function myfunc { commands; }`, is correct because the `function` keyword alone followed by the name and a compound command body is a valid Bash function definition form. Option E, `myfunc() { commands; }`, is correct because the POSIX-standard form using the name, empty parentheses, and a brace-delimited body is fully supported by Bash.

Option B is invalid because `myfunc = () { commands; }` includes an illegal space and equals sign, which Bash would treat as a command assignment, not a function definition. Option D is invalid because `def` is not a Bash keyword; it is used in Python, so Bash would attempt to run `def` as a command and fail.

Exam trap

The trap here is that candidates may think the 'function' keyword requires parentheses or that parentheses alone are insufficient, but Bash accepts both with and without the keyword, leading to confusion about which combinations are valid.

71
MCQmedium

In a Bash script, a variable is assigned the output of a command using: result=$(ls -l). What is the purpose of the $() syntax?

A.It runs the command and assigns its output to the variable
B.It expands the variable result
C.It checks if the command exists
D.It runs the command in a subshell and discards output
AnswerA

Command substitution executes the enclosed command in a subshell and replaces the expression with its standard output, which is then assigned to the variable. This lets result capture the directory listing text rather than the literal string, satisfying the script's intent.

Why this answer

The $() syntax is command substitution: Bash executes the command inside the parentheses in a subshell, captures its standard output, and substitutes that text into the assignment. So 'result=$(ls -l)' stores the directory listing in the variable result. This is the modern, nestable form of the older backtick syntax.

Exam trap

The trap is confusing command substitution $() with variable expansion ${}, causing candidates to pick the 'expands the variable' distractor.

How to eliminate wrong answers

Option B is wrong because variable expansion uses ${result} or $result, not $(); $() performs command substitution, not variable expansion. Option C is wrong because checking whether a command exists is done with 'command -v' or 'type', not $(). Option D is wrong because while $() does run the command in a subshell, it captures and returns the output rather than discarding it; discarding output would require redirecting to /dev/null.

72
MCQmedium

A system administrator needs to update a configuration file on multiple servers using Ansible. The playbook must ensure the line 'MaxAuthTries 3' is present in /etc/ssh/sshd_config. Which Ansible module is most appropriate?

A.template
B.shell
C.copy
D.lineinfile
AnswerD

lineinfile manages individual lines within an existing file, adding 'MaxAuthTries 3' if absent and matching by regexp. This satisfies the requirement to ensure a specific configuration line is present across multiple servers without rewriting the whole file.

Why this answer

The lineinfile module ensures a specific line is present in a file, ideal for configuration management.

73
MCQhard

In a bash script, a variable is set as follows: myvar='Hello World'. Which of the following correctly prints the first 5 characters of the variable?

A.echo ${myvar#?????}
B.echo ${myvar:0:5}
C.echo ${myvar:0-5}
D.echo ${myvar:5}
AnswerB

Bash substring expansion uses ${parameter:offset:length}, so ${myvar:0:5} extracts five characters starting at index zero, yielding "Hello". The offset is zero-based, and the length is explicit, which is exactly what printing the first five characters requires.

Why this answer

Bash parameter expansion supports substring extraction using the syntax ${variable:offset:length}. With myvar='Hello World', ${myvar:0:5} starts at index 0 and returns 5 characters, yielding 'Hello'. This is the standard, portable way to slice a string in Bash.

Exam trap

The trap is mixing up prefix/suffix pattern removal (# and %) with substring extraction (:offset:length); candidates often pick ${myvar#?????} thinking # means 'take' rather than 'strip'.

How to eliminate wrong answers

Option A is wrong because ${myvar#?????} uses pattern removal with the # operator, which strips the shortest matching prefix of five characters, leaving ' World' (the remainder), not the first five characters. Option C is wrong because ${myvar:0-5} is not valid Bash substring syntax; the offset/length form requires a colon between offset and length, and '0-5' would be interpreted as arithmetic yielding -5, which is not the intended slice. Option D is wrong because ${myvar:5} returns the substring starting at index 5 to the end (' World'), not the first five characters.

74
Multi-Selecthard

An administrator is debugging a Docker container that exits immediately after starting. Which THREE commands can help diagnose the issue? (Select THREE).

Select 3 answers
A.docker run --rm -it <image> sh
B.docker logs <container>
C.docker inspect <container>
D.docker exec -it <container> sh
E.docker ps
AnswersA, B, C

Overriding the image's default entrypoint with an interactive shell keeps the container running and exposes its filesystem, letting you inspect why the original command exited. This directly addresses the immediate-exit symptom by bypassing the failing startup command.

Why this answer

Option A (docker run --rm -it <image> sh) is correct because it overrides the image's default entrypoint/command with an interactive shell, letting you explore the filesystem and manually run the failing process to see errors directly. Option B (docker logs <container>) is correct because it retrieves stdout/stderr captured from the container's main process, which typically contains the crash message or stack trace explaining the immediate exit. Option C (docker inspect <container>) is correct because it reveals the container's ExitCode, State, Error, and the configured Entrypoint/Cmd, helping identify misconfigurations or non-zero exit reasons.

Option D (docker exec -it <container> sh) does not belong because exec requires a running container, and this container has already exited. Option E (docker ps) does not belong because it only lists running containers by default, so the exited container would not appear unless -a is used, and it provides no diagnostic detail.

Exam trap

The trap here is that candidates may select docker exec or docker ps, but exec requires a running container, and ps without -a does not show exited containers; the exam tests knowledge of which commands work on stopped containers.

75
MCQhard

A Linux administrator is troubleshooting a Bash script that unexpectedly terminates when a command fails. The script uses `#!/bin/bash`. Which of the following commands, if placed at the beginning of the script, would cause it to exit on any command failure?

A.set -u
B.trap 'exit 1' ERR
C.set -e
D.set -o pipefail
AnswerC

`set -e` makes Bash exit immediately when any command returns a non-zero status, which is exactly the failure-termination behaviour described. The shebang already invokes Bash, so this shell option applies. It satisfies the requirement to exit on any command failure.

Why this answer

The `set -e` option makes the shell exit immediately if a command exits with a non-zero status.

Page 1 of 2 · 112 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Lxp Scripting Containers questions.