Courseiva

CCNA Shells, Scripting and Data Management Questions

57 questions · Shells, Scripting and Data Management · All types, answers revealed

1
MCQmedium

A senior administrator runs a script that processes a CSV file. The script contains the following snippet: 'for field in $(cat data.csv); do ...'. The data.csv file contains lines like: 'John Doe, 123 Main St, Springfield'. The script fails to process correctly, splitting fields incorrectly and causing errors. Which of the following is the most appropriate fix?

A.Use xargs to process each line
B.Use 'for field in $(<data.csv)' with proper quoting
C.Use 'for field in "$(cat data.csv)"' with double quotes around the substitution
D.Use a while loop with read: 'while IFS= read -r line; do ... done < data.csv'
AnswerD

Reads each line correctly with IFS= to preserve whitespace.

Why this answer

The script fails due to word splitting and globbing when iterating over the output of `cat data.csv` with a `for` loop. Using `while IFS= read -r line` reads each line verbatim, preserving spaces and commas, and is the standard pattern for processing CSV or delimited files line by line in bash.

Exam trap

The trap here is that candidates often think quoting the command substitution or using `xargs` will fix the splitting issue, but they fail to recognize that `for` inherently splits on IFS, whereas `while read` processes one line at a time without word splitting.

How to eliminate wrong answers

Option A is wrong because `xargs` by default splits input on whitespace and newlines, which would still break fields containing spaces like 'John Doe' and does not address the core issue of reading entire lines. Option B is wrong because `$(<data.csv)` is equivalent to `$(cat data.csv)` and still undergoes word splitting and globbing, so fields with spaces or special characters are incorrectly split. Option C is wrong because double quotes around the command substitution `"$(cat data.csv)"` would treat the entire file as a single string, causing the loop to iterate only once over the whole file content, not per line.

2
MCQmedium

Refer to the exhibit. A user gets this error when running a script. What is the most likely cause?

A.The script is missing a shebang line.
B.The script has Windows-style line endings (CRLF).
C.The script does not have execute permission.
D.The script contains a syntax error in line 3.
AnswerB

The carriage return character (CR) is interpreted as a command, indicating CRLF line endings.

Why this answer

The error message shown in the exhibit (typically '/bin/bash^M: bad interpreter' or similar) indicates that the script contains carriage return characters (CR, \r) at the end of lines, which is characteristic of Windows-style CRLF line endings. When Linux's Bash tries to interpret the shebang line, it sees '/bin/bash^M' as the interpreter path, which does not exist, causing the script to fail. This is a common issue when scripts are created or edited on Windows and then transferred to a Unix-like system without converting line endings.

Exam trap

The LPI exam often tests the distinction between permission errors (chmod) and interpreter errors (shebang/line endings), trapping candidates who assume any script execution failure is due to missing execute permissions.

How to eliminate wrong answers

Option A is wrong because a missing shebang line would cause the script to be executed by the default shell (usually /bin/sh) or produce a different error (e.g., 'command not found'), not the specific 'bad interpreter' error shown. Option C is wrong because missing execute permission would produce a 'Permission denied' error, not an interpreter-related error. Option D is wrong because a syntax error in line 3 would only be detected after the script starts executing, and the error message would reference a syntax issue (e.g., 'syntax error near unexpected token'), not a missing interpreter.

3
MCQhard

A script reads a CSV file where fields may contain commas within quoted strings. Which approach correctly parses such fields?

A.Using 'cut -d',' -f1,2 file'
B.Using 'while IFS= read -r line; do ... done < file' and parsing manually
C.Using 'while IFS=',' read -r f1 f2; do ... done < file'
D.Using awk or a dedicated tool like csvkit
AnswerD

awk can handle quoted fields with FPAT; csvkit is purpose-built.

Why this answer

CSV fields containing commas within quoted strings require a parser that understands CSV quoting rules. Awk can be scripted to handle quoted fields, and dedicated tools like csvkit (e.g., csvcut, csvformat) are designed specifically to parse CSV according to RFC 4180, correctly ignoring commas inside double-quoted strings.

Exam trap

The trap here is that candidates assume simple field-splitting tools like 'cut' or 'read' with IFS=',' can handle CSV, but they fail to account for commas inside quoted strings, which is a classic LPIC-1 data management pitfall.

How to eliminate wrong answers

Option A is wrong because 'cut -d',' -f1,2 file' splits on every comma, including those inside quoted strings, corrupting the field boundaries. Option B is wrong because 'while IFS= read -r line; do ... done < file' reads entire lines but manual parsing of quoted commas is error-prone and requires complex state-machine logic, not a simple approach. Option C is wrong because 'while IFS=',' read -r f1 f2; do ... done < file' splits on every comma, treating commas inside quotes as field separators, which breaks the CSV structure.

4
MCQeasy

A cron job is configured to run a script every day at 2:30 AM. The sysadmin notices the job runs but produces no output. Which is the most likely reason?

A.The cron daemon is not running.
B.The script requires a terminal to run.
C.The MAILTO environment variable is not set, and the output is not redirected.
D.Cron automatically suppresses all output.
AnswerC

Cron emails output only if MAILTO is set; otherwise, output is lost.

Why this answer

Cron jobs run in a non-interactive, non-terminal environment. By default, cron captures any output (stdout/stderr) from the job and attempts to email it to the user. If the MAILTO variable is not set and the output is not redirected to a file or /dev/null, the output is simply discarded, resulting in no visible output.

The job still runs successfully, but the output is lost.

Exam trap

The trap here is that candidates often assume cron silently discards all output by default, when in fact cron attempts to mail it, and the 'no output' symptom is due to the output being sent to an unmonitored mailbox or not redirected.

How to eliminate wrong answers

Option A is wrong because if the cron daemon were not running, the job would not run at all, but the question states the job runs. Option B is wrong because cron jobs do not require a terminal; they run in a minimal environment without a controlling terminal, and scripts that need a terminal would typically fail or hang, not produce no output. Option D is wrong because cron does not automatically suppress all output; it captures output and either mails it or discards it based on configuration.

5
MCQhard

A script starts multiple background processes. An administrator wants to wait for all background jobs to complete before proceeding. Which command should be used?

A.jobs -l
B.wait %1
C.wait
D.sleep 5
AnswerC

Waits for all background jobs to complete.

Why this answer

The `wait` command without any arguments waits for all background jobs spawned by the current shell to complete before returning control to the script. This is the correct way to synchronize multiple background processes in a shell script, ensuring all child processes finish before proceeding to the next command.

Exam trap

The trap here is that candidates often confuse `wait` with `jobs` or assume that a fixed sleep duration is sufficient, not realizing that `wait` is the only command that dynamically synchronizes with the actual completion of all background jobs.

How to eliminate wrong answers

Option A is wrong because `jobs -l` lists background jobs with their process IDs but does not wait for them to finish; it merely displays their status. Option B is wrong because `wait %1` waits only for the specific job with job specifier `%1` (the first background job), not all background jobs. Option D is wrong because `sleep 5` simply pauses execution for 5 seconds and does not guarantee that any background jobs have completed; it is a fixed delay, not a synchronization mechanism.

6
Multi-Selecthard

When writing a Bash script, which two constructs can be used to safely iterate over a list of filenames that may contain spaces or special characters? (Choose TWO)

Select 2 answers
A.for file in *.txt; do ... done
B.find . -name '*.txt' -exec echo {} \;
C.for file in $(find . -name '*.txt'); do ... done
D.while IFS= read -r file; do ... done < <(find . -name '*.txt' -print0)
E.for file in "*.txt"; do ... done
AnswersB, D

Executes a command per file without shell word splitting.

Why this answer

The `-exec` action in `find` passes each filename as a separate argument to the command, avoiding word splitting and glob expansion. This ensures that filenames containing spaces, tabs, or newlines are handled safely without being broken into multiple arguments.

Exam trap

The trap here is that candidates often assume command substitution (`$(...)`) or simple glob expansion safely handles filenames with spaces, but the shell performs word splitting and glob expansion on the unquoted result, leading to broken loops or security issues.

7
MCQmedium

A system administrator wants to monitor a log file in real-time for lines containing 'ERROR' and write them to a separate file. Which command combination is most appropriate?

A.less logfile
B.tail -f logfile | grep 'ERROR' > error.log
C.vi logfile
D.cat logfile | grep 'ERROR' > error.log
AnswerB

tail -f provides real-time output, grep filters.

Why this answer

`tail -f logfile` continuously outputs new lines appended to the file, and piping that output into `grep 'ERROR'` filters only lines containing 'ERROR', which are then redirected to `error.log`. This combination achieves real-time monitoring and selective logging without blocking the terminal or requiring manual intervention.

Exam trap

The trap here is that candidates may confuse `cat` with `tail -f`, thinking both can monitor a file in real time, but `cat` only dumps the current content and exits, while `tail -f` actively follows appended data.

How to eliminate wrong answers

Option A is wrong because `less logfile` is a pager for viewing file contents interactively; it does not provide real-time updates and cannot automatically filter lines to a separate file. Option C is wrong because `vi logfile` opens the file in a text editor, which is not designed for real-time monitoring or automated filtering and redirection. Option D is wrong because `cat logfile | grep 'ERROR' > error.log` only processes the current contents of the file at the moment of execution; it does not monitor for new lines appended in real time.

8
Drag & Dropmedium

Order the steps to add a new user to the system and grant sudo privileges.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

User creation uses useradd, then password is set, and adding to sudo group grants privileges.

9
MCQeasy

Refer to the exhibit. An administrator wants to unset the BASH_ALIASES associative array. Which command will correctly remove it?

A.export -n BASH_ALIASES
B.unset -v BASH_ALIASES
C.delete BASH_ALIASES
D.unset BASH_ALIASES
AnswerD

Correctly unsets the variable or array.

Why this answer

`unset` is the standard Bash built-in command to destroy a variable or function. For an associative array like BASH_ALIASES, `unset BASH_ALIASES` removes the entire array, including all its key-value pairs, from the current shell environment.

Exam trap

The trap here is that candidates may confuse `unset` with `export -n` or think a special flag like `-v` is required, when in fact `unset` alone is the correct and simplest way to remove any variable, including associative arrays.

How to eliminate wrong answers

Option A is wrong because `export -n` removes the export attribute from a variable but does not unset or delete the variable itself; the variable remains in the shell with its value intact. Option B is wrong because `unset -v` is valid for unsetting a variable, but the `-v` flag is unnecessary and not required for associative arrays; the plain `unset` command already handles variables correctly, and adding `-v` does not change behavior but is not the standard form for this task. Option C is wrong because `delete` is not a valid Bash built-in command; it is a common misconception from other shells or programming languages, and Bash has no `delete` command.

10
MCQhard

A script uses a while loop to read lines from a file, but a variable set inside the loop is empty after the loop finishes. What is the most likely cause?

A.The file has an empty line at the end.
B.The variable is declared as readonly.
C.The variable name contains spaces.
D.The while loop is part of a pipeline, causing it to run in a subshell.
AnswerD

Pipeline subshells isolate variable changes.

Why this answer

When a while loop is part of a pipeline (e.g., `while read line; do ... done < file | command` or `command | while read line; do ... done`), each command in the pipeline runs in its own subshell. Variables set inside the subshell are not propagated back to the parent shell, so they appear empty after the loop finishes. This is a common pitfall in shell scripting.

Exam trap

The trap here is that candidates often overlook the subshell behavior of pipelines and incorrectly attribute the issue to file content or variable declaration errors, rather than recognizing that the pipeline creates a separate shell environment.

How to eliminate wrong answers

Option A is wrong because an empty line at the end of a file does not cause variables set inside a while loop to become empty after the loop; it may affect the loop's iteration count but not variable scope. Option B is wrong because a readonly variable would cause an error when trying to assign to it, not silently become empty after the loop. Option C is wrong because variable names with spaces are syntactically invalid in shell scripts and would cause a syntax error, not a post-loop empty value.

11
MCQeasy

A system administrator wants to display all lines in /var/log/syslog that do NOT contain the string 'error'. Which command accomplishes this?

A.grep -v 'error' /var/log/syslog
B.grep -r 'error' /var/log/syslog
C.grep -l 'error' /var/log/syslog
D.grep -i 'error' /var/log/syslog
AnswerA

Inverts match, showing only lines without 'error'.

Why this answer

The `grep -v` option inverts the match, displaying only lines that do NOT contain the pattern. Therefore, `grep -v 'error' /var/log/syslog` outputs all lines from the file that lack the string 'error', which directly fulfills the requirement.

Exam trap

The trap here is that candidates often confuse `-v` (invert match) with `-i` (case-insensitive) or `-r` (recursive), leading them to select options that still show matching lines instead of excluding them.

How to eliminate wrong answers

Option B is wrong because `-r` enables recursive search through directories, not line inversion; it would search for lines containing 'error' in the file and any subdirectories, which is not the intended behavior. Option C is wrong because `-l` lists only filenames (not lines) that contain the pattern, so it would output the filename if 'error' is found anywhere, not the lines without 'error'. Option D is wrong because `-i` performs case-insensitive matching, still showing lines that contain 'error' (or 'Error', 'ERROR', etc.), which is the opposite of what is asked.

12
MCQmedium

A log file access.log contains multiple entries per IP address. An administrator wants to display a list of unique IP addresses sorted by frequency (most frequent first). Which command pipeline achieves this?

A.awk '{print $1}' access.log | sort | uniq | sort -rn
B.awk '{print $1}' access.log | sort | uniq -c | sort -rn
C.awk '{print $1}' access.log | sort -rn | uniq -c
D.awk '{print $1}' access.log | sort | uniq -c | sort -k2
AnswerB

Correctly counts IP occurrences and sorts by frequency descending.

Why this answer

It extracts the first field (IP address) with awk, sorts them to group identical IPs, counts occurrences with uniq -c, and then sorts numerically in reverse order with sort -rn to display the most frequent IPs first. The -c flag prepends a count to each unique line, and sort -rn sorts by that count descending.

Exam trap

The trap here is that candidates often forget uniq -c outputs the count in the first column, so they mistakenly use sort -k2 to sort by frequency, or they omit the initial sort before uniq, causing incorrect counts for non-consecutive duplicates.

How to eliminate wrong answers

Option A is wrong because uniq without -c only removes duplicates, not counting them, and sort -rn then sorts the IPs themselves in reverse numeric order, not by frequency. Option C is wrong because sort -rn before uniq -c sorts IPs numerically descending, which is meaningless for IP addresses, and uniq -c then counts consecutive duplicates only, missing non-consecutive duplicates. Option D is wrong because sort -k2 sorts by the second field, but uniq -c outputs the count as the first field, so sort -k2 sorts by the IP address (second field) instead of by frequency.

13
MCQmedium

A developer has a directory /home/user/project with many files and subdirectories. They need to change the group ownership of all .txt files to 'developers' and set permissions to 640. Which single command accomplishes this?

A.find /home/user/project -name '*.txt' -exec chgrp developers {} \;
B.chmod -R 640 /home/user/project/*.txt
C.find /home/user/project -name '*.txt' -exec chown :developers {} \; -exec chmod 640 {} \;
D.find /home/user/project -name '*.txt' -exec chmod 640 {} \;
AnswerC

Changes both group and permissions in a single find command.

Why this answer

It uses `find` to locate all `.txt` files under `/home/user/project`, then executes `chown :developers` to change the group ownership to 'developers' (the colon before the group name is the correct syntax for setting only the group), followed by `chmod 640` to set the permissions to read/write for the owner and read for the group. Using `-exec` twice in a single `find` command ensures both operations are applied to each matching file without needing a separate command.

Exam trap

The trap here is that candidates often forget that `chmod` alone cannot change ownership, or they mistakenly think `chown :group` is invalid, leading them to pick an incomplete command like A or D, or they incorrectly assume `chmod -R` with a glob will recurse into subdirectories.

How to eliminate wrong answers

Option A is wrong because it only changes the group ownership to 'developers' but does not set the permissions to 640, leaving the permissions unchanged. Option B is wrong because `chmod -R 640 /home/user/project/*.txt` will fail if the glob `*.txt` expands to no files (or only files in the top directory), and it does not change group ownership; also `-R` is redundant for individual files and does not recurse into subdirectories for the glob pattern. Option D is wrong because it only sets permissions to 640 but does not change the group ownership to 'developers'.

14
MCQmedium

Refer to the exhibit. An application uses this JSON policy to control execution of commands. If a user tries to run /usr/bin/passwd, what will happen?

A.Denied because the deny rule is more specific.
B.Allowed because the allow rule matches.
C.The policy is invalid due to conflicting rules.
D.The path pattern does not match.
AnswerA

The deny rule explicitly blocks /usr/bin/passwd, so execution is denied.

Why this answer

The deny rule is more specific than the allow rule. In this JSON policy, the deny rule explicitly matches the exact path `/usr/bin/passwd`, while the allow rule uses a wildcard pattern `*` that matches all commands. When a more specific rule (deny) conflicts with a less specific rule (allow), the more specific rule takes precedence, so the execution is denied.

Exam trap

The trap here is that candidates assume the allow rule's wildcard `*` always grants access, ignoring that a more specific deny rule takes precedence over a broader allow rule.

How to eliminate wrong answers

Option B is wrong because even though the allow rule matches all commands via the wildcard `*`, the deny rule is more specific to `/usr/bin/passwd` and overrides the broader allow rule. Option C is wrong because the policy is not invalid; conflicting rules are resolved by specificity, and the policy is syntactically valid JSON. Option D is wrong because the path pattern `/usr/bin/passwd` in the deny rule exactly matches the command the user tries to run, so the pattern does match.

15
Matchingmedium

Match each package manager to its associated distribution family.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Debian, Ubuntu

RHEL, CentOS 7

Fedora, RHEL 8+

openSUSE

Arch Linux

Why these pairings

Common package managers and their distribution families: APT (Debian), YUM/DNF (Red Hat), ZYpp (SUSE), pacman (Arch). Distractor options swap these associations.

16
MCQmedium

A system administrator writes a script that extracts data from a CSV file and inserts it into a database. The script works correctly when run manually but fails when executed by cron. Which environment variable is most likely causing the issue?

A.SHELL
B.LANG
C.HOME
D.PATH
AnswerD

PATH is often not set in cron, causing command not found errors.

Why this answer

When a script runs manually, the user's interactive shell inherits a fully populated PATH environment variable that includes directories like /usr/local/bin, /usr/bin, and possibly custom script directories. Cron jobs, however, execute with a minimal environment, and the default PATH for cron is often just /usr/bin:/bin. If the script relies on commands (e.g., mysql, psql, or custom scripts) located outside these directories, cron will fail with a 'command not found' error.

Setting the full PATH explicitly inside the script or in the crontab file resolves the issue.

Exam trap

The trap here is that candidates often assume the script's failure is due to a missing HOME or SHELL variable, but the most frequent cron-related issue is the restricted PATH environment, which prevents the script from locating executables.

How to eliminate wrong answers

Option A is wrong because SHELL defines the shell binary used to interpret the script (e.g., /bin/bash), but cron already uses the user's default shell from /etc/passwd; a mismatch would cause syntax errors, not a missing command failure. Option B is wrong because LANG affects locale settings like character encoding and sorting order, which could cause data corruption or sorting issues but not a complete failure to execute commands. Option C is wrong because HOME defines the user's home directory; while some scripts may rely on relative paths or config files in ~, the most common cron failure is due to a truncated PATH, not a missing HOME.

17
MCQhard

A developer needs to ensure a bash script exits immediately if any command fails, and also prints each command before executing it. Which set of shell options should be used at the beginning of the script?

A.set -ex
B.set -e
C.set -vx
D.set -ux
AnswerA

-e exits on error, -x prints commands.

Why this answer

`set -ex` combines two essential shell options: `-e` (errexit) causes the script to exit immediately if any command returns a non-zero exit status, and `-x` (xtrace) prints each command (after expansion) to stderr before executing it. This is the standard way to achieve both behaviors in a single line, as required by the question.

Exam trap

The trap here is that candidates often confuse `-v` (verbose, which prints input lines as read) with `-x` (xtrace, which prints commands before execution), or forget that `-e` is required for exit-on-error, leading them to pick `set -vx` or `set -ux` instead of the correct `set -ex`.

How to eliminate wrong answers

Option B is wrong because `set -e` only enables exit-on-error but does not print commands before execution, missing the requirement to print each command. Option C is wrong because `set -vx` enables verbose mode (`-v`, which prints shell input lines as they are read) and xtrace (`-x`), but verbose mode does not print commands before execution in the same way as `-x`; the question specifically asks for printing each command before executing it, which is `-x`'s behavior, and `-v` is redundant or incorrect for this purpose. Option D is wrong because `set -ux` enables nounset (`-u`, which treats unset variables as an error) and xtrace (`-x`), but does not enable exit-on-error (`-e`), so the script will not exit immediately if a command fails.

18
MCQeasy

Which sed command will replace the first occurrence of 'foo' with 'bar' on each line of a file?

A.sed 's/foo/bar/g' file
B.sed 's/foo/bar/0' file
C.sed 's/foo/bar/2' file
D.sed 's/foo/bar/' file
AnswerD

Default replaces first occurrence per line.

Why this answer

The default behavior of the `s` (substitute) command in sed is to replace only the first occurrence of the pattern on each line. Without a numeric flag, `sed 's/foo/bar/' file` replaces the first 'foo' on each line with 'bar'. The `g` flag would replace all occurrences, not just the first.

Exam trap

The trap here is that candidates often confuse the default behavior of sed's substitute command, assuming it replaces all occurrences unless told otherwise, and thus incorrectly choose the `g` flag option.

How to eliminate wrong answers

Option A is wrong because the `g` flag causes sed to replace all occurrences of 'foo' with 'bar' on each line, not just the first. Option B is wrong because sed does not support a `0` flag for the substitute command; the numeric flag must be a positive integer, and `0` is invalid or ignored. Option C is wrong because the `2` flag replaces the second occurrence of 'foo' on each line, not the first.

19
MCQeasy

An administrator wants to list all lines in a log file that do NOT contain the word 'ERROR'. Which command should be used?

A.grep -i 'ERROR' logfile
B.grep -w 'ERROR' logfile
C.grep -v 'ERROR' logfile
D.grep 'ERROR' logfile
AnswerC

The -v option inverts the match.

Why this answer

The `-v` flag inverts the match, causing `grep` to output only lines that do NOT contain the pattern 'ERROR'. This is the standard way to exclude lines matching a pattern in a file.

Exam trap

The trap here is that candidates often confuse the `-v` invert-match flag with other common flags like `-i` (case-insensitive) or `-w` (whole-word), or simply forget that `grep` by default shows matching lines, not excluding them.

How to eliminate wrong answers

Option A is wrong because `-i` performs a case-insensitive search, which would still show lines containing 'ERROR' (or 'error', 'Error', etc.), not exclude them. Option B is wrong because `-w` matches whole words only, but it still selects lines containing 'ERROR', not excludes them. Option D is wrong because it simply prints all lines containing 'ERROR', which is the opposite of what the administrator wants.

20
MCQeasy

A user reports that running '/usr/local/bin/myapp' from the command line results in 'bash: /usr/local/bin/myapp: No such file or directory'. The exhibit shows the file exists and is a valid executable. What is the most likely cause of the error?

A.The script interpreter specified in the shebang is missing.
B.The library libc.so.6 is missing.
C.The dynamic linker /lib64/ld-linux-x86-64.so.2 is missing or corrupted.
D.The file does not have execute permission for the user.
AnswerC

The binary uses this interpreter; if missing, loading fails.

Why this answer

When a dynamically linked executable exists and is valid but fails with 'No such file or directory', the most common cause is that the dynamic linker (e.g., /lib64/ld-linux-x86-64.so.2) is missing or corrupted. Bash reports this error because the kernel's execve() syscall cannot find the interpreter specified in the ELF's PT_INTERP segment, not because the executable itself is absent. This is a classic symptom distinct from a missing library, which would produce 'error while loading shared libraries'.

Exam trap

The trap here is that candidates confuse the 'No such file or directory' error for the executable itself with a missing library or permission issue, but the error actually refers to the dynamic linker that the executable depends on, not the executable file.

How to eliminate wrong answers

Option A is wrong because a missing script interpreter (e.g., /usr/bin/python) would produce a different error like 'bad interpreter: No such file or directory' or 'command not found', not the generic 'No such file or directory' for the executable path itself. Option B is wrong because a missing library such as libc.so.6 would cause a runtime error like 'error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory', not the initial 'No such file or directory' for the executable. Option D is wrong because missing execute permission would produce 'Permission denied', not 'No such file or directory'.

21
MCQhard

A systems administrator maintains a Linux web server running Apache HTTP Server (version 2.4) with three virtual hosts. The server logs are stored in /var/log/httpd/ and are rotated using logrotate, which is configured with the default settings that came with the Apache package. The administrator has noticed that after the nightly log rotation, the main access log file (access_log) is empty, while the rotated log files (e.g., access_log.1, access_log.2) contain the previous day's data. Furthermore, new HTTP requests are being logged into the most recent rotated file (access_log.1) instead of the current access_log file. The administrator has verified that the logrotate cron job runs successfully, and that the log files are owned by the root user with read/write permissions for the root group. No errors appear in the system logs. The Apache service continues to run and serve web pages. Which of the following actions should the administrator take to ensure that Apache writes new log entries to the current access_log file after rotation?

A.Modify the Apache configuration to set the 'RotateLogs' directive and restart the service.
B.Add a postrotate script to the logrotate configuration that sends a USR1 or HUP signal to the Apache process to cause it to reopen the log files.
C.Change the logrotate frequency to 'weekly' so that the log is not rotated as often.
D.Set the 'copytruncate' directive in the logrotate configuration to copy the log file and truncate the original, so Apache can continue writing without interruption.
AnswerB

This is the standard method: after rotation, Apache needs to be signaled to reopen the log files to write to the new file.

Why this answer

The issue is that after logrotate moves the current access_log to access_log.1, Apache continues writing to the old file descriptor (now pointing to access_log.1) because it never reopened the log file. Sending a USR1 or HUP signal to Apache causes it to close and reopen its log files, creating a new access_log and writing new entries there. This is the standard method for log rotation with Apache and other daemons that keep file handles open.

Exam trap

The trap here is that candidates may think 'copytruncate' is a safe, signal-free solution, but they overlook the risk of data loss between the copy and truncate operations, making the postrotate signal method the correct and reliable choice for Apache.

How to eliminate wrong answers

Option A is wrong because Apache 2.4 does not have a 'RotateLogs' directive; log rotation is handled externally by logrotate, not by Apache itself. Option C is wrong because changing the frequency to weekly does not fix the core problem of Apache writing to the wrong file after rotation; it only delays the issue. Option D is wrong because 'copytruncate' would copy the log and truncate the original, which avoids the need for a signal, but it can cause data loss (entries written between copy and truncate) and is not the standard or recommended approach for Apache; the correct method is to use a postrotate script with a signal.

22
MCQhard

A directory contains files with spaces and special characters in their names. An administrator wants to delete all files older than 30 days using find and xargs. Which command is safe?

A.find /path -type f -mtime +30 -delete
B.find /path -type f -mtime +30 -exec rm {} \;
C.find /path -type f -mtime +30 | xargs rm
D.find /path -type f -mtime +30 -print0 | xargs -0 rm
AnswerD

Uses null delimiter to safely handle any filename.

Why this answer

It uses `-print0` with `find` to output null-delimited filenames, and `xargs -0` to process them safely. This handles spaces, newlines, and special characters in filenames without word-splitting or shell interpretation, ensuring all matching files older than 30 days are deleted reliably.

Exam trap

The trap here is that candidates often choose option C, overlooking the fact that default xargs splits on whitespace and interprets quotes, making it unsafe for filenames with spaces or special characters, while `-print0` and `-0` are the correct safe approach.

How to eliminate wrong answers

Option A is wrong because `-delete` is not a standard POSIX find option and may not be available on all systems; it also does not use xargs as required. Option B is wrong because `-exec rm {} \;` forks a new rm process for each file, which is inefficient and does not use xargs. Option C is wrong because piping `find` output directly to `xargs rm` without `-print0` and `-0` causes filenames with spaces or special characters to be split into multiple arguments, leading to errors or unintended deletions.

23
Multi-Selectmedium

Which TWO of the following are true about the 'source' command in bash?

Select 2 answers
A.It executes a script in a subshell.
B.It is only available in bash and not in POSIX sh.
C.It can be abbreviated as '.' (dot).
D.It executes a script in the current shell.
E.It requires the script to have execute permission.
AnswersC, D

The dot is a synonym for source.

Why this answer

The 'source' command can be abbreviated as a single dot ('.') in bash and other POSIX-compliant shells. This dot notation is a standard feature defined by POSIX, and both forms execute the script in the current shell environment, not a subshell.

Exam trap

The trap here is that candidates often confuse 'source' with executing a script directly (which requires execute permission and runs in a subshell), or mistakenly think the dot abbreviation is a bash-only feature, when it is actually defined by POSIX.

24
Multi-Selecteasy

Which TWO of the following are valid ways to capture the output of a command into a variable in Bash?

Select 2 answers
A.var=`command`
B.var={command}
C.var=$(command)
D.var|command
E.var=command
AnswersA, C

Backticks are an older syntax for command substitution, but still valid.

Why this answer

Both var=`command` (backticks) and var=$(command) (dollar-parentheses) are valid command substitution syntaxes in Bash. While backticks are older and can cause issues with nesting, they are still valid and widely used. Option B uses braces, which is not a valid syntax.

Option D uses a pipe, which is for chaining commands, not variable assignment. Option E assigns the literal string 'command' to the variable, not the output of the command. Therefore, A and C are the correct choices.

Exam trap

LPI often tests the distinction between command substitution syntax and other shell constructs like brace expansion or simple assignment, leading candidates to confuse var=$(command) with var={command} or var=command.

25
MCQmedium

A script running as a daemon should perform clean-up operations when it receives SIGTERM. Which command inside the script sets up this behavior?

A.trap cleanup TERM
B.trap 'cleanup' SIGTERM
C.trap 'cleanup' EXIT
D.trap "cleanup" 9
AnswerB

Sets a trap for SIGTERM to run the cleanup function.

Why this answer

The `trap` command in Bash allows a script to catch signals and execute specified commands. The syntax `trap 'cleanup' SIGTERM` registers the `cleanup` function or command to run when the SIGTERM signal (signal 15) is received, which is the standard signal sent by `systemctl stop` or `kill` to request graceful termination of a daemon. This ensures the daemon performs clean-up operations before exiting.

Exam trap

The trap here is that candidates confuse signal names with signal numbers or mix up SIGTERM (15, catchable) with SIGKILL (9, uncatchable), or they incorrectly assume the EXIT pseudo-signal is equivalent to SIGTERM, when in fact EXIT triggers on any script termination, not specifically on a SIGTERM request.

How to eliminate wrong answers

Option A is wrong because `trap cleanup TERM` omits the quotes around the command string; while it may work in some shells if `cleanup` is a simple command, the correct syntax for a function or multi-word command requires quotes to prevent immediate expansion or misinterpretation. Option C is wrong because `trap 'cleanup' EXIT` catches the EXIT pseudo-signal, which triggers when the script exits for any reason (including normal exit or SIGINT), not specifically for SIGTERM, so it does not set up behavior for the SIGTERM signal itself. Option D is wrong because `trap "cleanup" 9` uses signal number 9, which is SIGKILL; SIGKILL cannot be caught, ignored, or trapped by a script, making this command invalid and the clean-up code will never execute.

26
MCQmedium

Given a file with lines like 'John:23:Engineer', which awk command prints only the name and department (first and third fields) separated by a space?

A.awk -F: '{print $1,$3}' file
B.awk -F: '{print $1,$2}' file
C.awk -F: '{print $1 $3}' file
D.awk -F: '{print $1 $2}' file
AnswerA

Comma in print outputs space separator.

Why this answer

The `-F:` flag sets the field separator to colon, and `{print $1,$3}` prints the first and third fields separated by the default output field separator (a space). This matches the requirement to output the name and department from lines like 'John:23:Engineer'.

Exam trap

The trap here is that candidates often confuse the comma (which inserts the OFS) with concatenation (no comma), leading them to pick options like C or D that produce no space between fields, or they misidentify the field numbers and select B instead of A.

How to eliminate wrong answers

Option B is wrong because `{print $1,$2}` prints the first and second fields (name and age), not the name and department. Option C is wrong because `{print $1 $3}` concatenates the first and third fields with no separator, producing output like 'JohnEngineer' instead of 'John Engineer'. Option D is wrong because `{print $1 $2}` concatenates the first and second fields with no separator, outputting 'John23' instead of the required name and department.

27
MCQmedium

A system administrator needs to ensure that a bash script continues executing even if any command in the script fails. Which of the following should be used at the beginning of the script?

A.set +e
B.trap 'echo error' ERR
C.unset -e
D.set -e
E.# set +e
AnswerA

Disables exit on error, allowing the script to continue.

Why this answer

`set +e` disables the 'exit on error' behavior in a bash script, allowing the script to continue executing even if a command returns a non-zero exit status. By default, bash scripts do not exit on error, but if `set -e` is used elsewhere, `set +e` explicitly turns that off to ensure the script continues despite failures.

Exam trap

The trap here is that candidates often confuse `set +e` with `set -e`, or think that a comment like `# set +e` would have any effect, when in fact the `+` sign disables the option and the `-` sign enables it.

How to eliminate wrong answers

Option B is wrong because `trap 'echo error' ERR` sets a trap that executes a command when a command fails, but it does not prevent the script from exiting; the script will still exit after the trap runs unless `set +e` is also used. Option C is wrong because `unset -e` is not a valid bash command; `unset` is used to unset variables or functions, not shell options. Option D is wrong because `set -e` enables 'exit on error', which causes the script to terminate immediately when any command fails, which is the opposite of what is needed.

Option E is wrong because `# set +e` is a comment and has no effect on shell behavior; the `#` makes it a comment line.

28
MCQmedium

Refer to the exhibit. What will be the output when this script is executed?

A.a b\nd e
B.a b c\nd e f
C.a b
D.The script will error because of incorrect read syntax.
AnswerB

Correct. Because `b` and `e` capture the remaining words from their respective lines, the output includes 'b c' and 'e f'.

Why this answer

The script reads two lines from standard input. The first `read a b` reads the first line 'a b c'. Since there are three words but only two variables, the last variable `b` captures the remainder of the line, so a='a' and b='b c'.

The second `read d e` reads the second line 'd e f', so d='d' and e='e f'. The `echo -e` command outputs the values with an escaped newline (`\n`) between them, producing two lines: 'a b c' and 'd e f', represented as 'a b c\nd e f'.

Exam trap

The trap is that `read` assigns the remainder of the line to the last variable when there are more words than variables. Candidates often think each variable gets exactly one word, but actually the last variable absorbs all remaining words.

How to eliminate wrong answers

Option B is wrong because it assumes `read` splits each line into three variables, but `read` assigns the remainder of the line to the last variable, so `b` gets 'b c' and `e` gets 'e f', not 'b' and 'e' alone. Option C is wrong because it only shows the first line, ignoring the second `read` that processes the second line. Option D is wrong because the `read` syntax is correct; `read` with multiple variables splits on whitespace and does not error when there are fewer variables than fields.

29
MCQhard

A script produces both standard output and error messages. An administrator wants to save the output to 'out.log' and the error messages to 'err.log', but also wants to see both on the terminal. Which command achieves this?

A../script.sh 2>&1 | tee out.log 2>&1 | tee err.log
B../script.sh > >(tee out.log) 2> >(tee err.log)
C../script.sh > out.log 2> err.log
D../script.sh 2>&1 | tee out.log
AnswerB

Uses process substitution to duplicate stdout to terminal and out.log, and stderr to terminal and err.log.

Why this answer

Uses process substitution to redirect stdout and stderr into separate tee commands, which both write to files and pass the streams through to the terminal. The syntax `> >(tee out.log)` redirects stdout to a tee process that writes to out.log and also echoes to the terminal, while `2> >(tee err.log)` does the same for stderr. This ensures both streams are saved to separate files and displayed on the terminal simultaneously.

Exam trap

The trap here is that candidates often confuse `2>&1` (which merges stderr into stdout) with separate stream handling, leading them to pick options that either lose terminal output or fail to keep stdout and stderr in distinct files.

How to eliminate wrong answers

Option A is wrong because it redirects stderr to stdout with `2>&1`, then pipes both to `tee out.log`, but the subsequent `2>&1 | tee err.log` is applied to the output of the first tee, not to the original script's stderr; this mixes streams and does not separate stdout and stderr into distinct files. Option C is wrong because `./script.sh > out.log 2> err.log` sends stdout to out.log and stderr to err.log, but neither stream appears on the terminal — the administrator wants to see both on the terminal. Option D is wrong because `2>&1 | tee out.log` merges stderr into stdout and sends the combined stream to tee, which writes to out.log and the terminal, but stderr is not saved separately to err.log.

30
MCQmedium

A shell script uses the variable expansion ${var:-default} to set a default value for an environment variable. The script prints unexpected output when the variable is set to an empty string. Which expansion should be used to ensure the default is only used when the variable is unset, not when it is empty?

A.${var:-default}
B.${var-default}
C.${var:?default}
D.${var:=default}
AnswerB

Only applies when var is unset.

Why this answer

The expansion `${var-default}` uses the default value only when the variable is unset (i.e., does not exist at all). In contrast, `${var:-default}` also substitutes the default when the variable is set but empty, which causes the unexpected output described in the question. The colon in the expansion is the critical difference: it adds the check for a null or empty string.

Exam trap

The trap here is that candidates often confuse the colon modifier, assuming `${var:-default}` and `${var-default}` behave identically, when in fact the colon adds the empty-string check that causes the unexpected behavior described in the question.

How to eliminate wrong answers

Option A is wrong because `${var:-default}` triggers the default when the variable is unset OR empty, which is exactly the behavior that produces the unexpected output when the variable is set to an empty string. Option C is wrong because `${var:?default}` causes the shell to exit with an error if the variable is unset or empty, rather than providing a default value. Option D is wrong because `${var:=default}` assigns the default value to the variable if it is unset or empty, modifying the variable itself, which is not the same as simply using a default without side effects.

31
MCQmedium

A systems administrator is responsible for a Linux server that runs a custom application. The application writes logs to /var/log/app.log and rotates them using logrotate. Recently, the server ran out of disk space because log files were not being rotated. The administrator checks the logrotate configuration file /etc/logrotate.d/app and finds: /var/log/app.log { weekly rotate 4 compress missingok notifempty } The administrator manually runs 'logrotate -f /etc/logrotate.d/app' and the log rotates successfully. However, the next day, the log is not rotated again. The administrator checks the cron job for logrotate and finds that /etc/cron.daily/logrotate exists and runs logrotate /etc/logrotate.conf. The administrator checks /etc/logrotate.conf and sees that it includes /etc/logrotate.d/*. What is the most likely reason the log is not rotating automatically?

A.The 'weekly' directive schedules rotation once per week, so the log will not be rotated again until a full week has passed.
B.The 'notifempty' directive is misspelled; it should be 'notifempty'.
C.The /etc/logrotate.d/ directory is not included by logrotate.conf.
D.The 'missingok' directive prevents rotation if the log file is missing, but the file exists.
AnswerA

Although the word 'weekly' is not misspelled, this option points to the root cause: the 'weekly' frequency prevents daily rotation. The manual forced rotation works because -f forces rotation regardless of frequency.

Why this answer

The 'weekly' directive is correctly spelled and instructs logrotate to rotate the log once per week. The cron job runs daily, but logrotate will only rotate when the specified time interval (one week) has passed since the last rotation. The forced rotation with -f succeeded because -f overrides all conditions, including the time interval.

The other options are incorrect: 'notifempty' is spelled correctly, /etc/logrotate.d/ is included via /etc/logrotate.conf, and 'missingok' is not the issue because the log file exists.

Exam trap

The trap is that candidates focus on the misspelling of 'notifempty' (which is actually correct) and overlook the more fundamental issue that the 'weekly' directive only rotates logs once a week, causing the automatic daily check to skip rotation.

How to eliminate wrong answers

Option A is wrong because 'weekly' is correctly spelled and is a valid logrotate directive. Option B is wrong because the misspelling 'notifempty' is not recognized by logrotate, causing it to be ignored; the correct directive is 'notifempty'. Option C is wrong because the administrator confirmed that /etc/logrotate.conf includes /etc/logrotate.d/*, so the directory is included.

Option D is wrong because 'missingok' does not prevent rotation if the file exists; it only suppresses errors if the log file is missing.

32
MCQhard

A script uses a here-document to pass multi-line input to a command. Which here-document syntax will prevent variable expansion inside the document?

A.<< EOF
B.<<- EOF
C.<< "EOF"
D.<< 'EOF'
AnswerD

Quoting the delimiter prevents expansion.

Why this answer

Single-quoting the delimiter (e.g., `<< 'EOF'`) prevents the shell from performing variable expansion and command substitution within the here-document. The shell treats the quoted delimiter literally, so all content between the start and end markers is passed verbatim to the command.

Exam trap

The trap here is that candidates mistakenly think double quotes (`<< "EOF"`) also prevent expansion, but in fact double quotes are removed by the shell and do not inhibit expansion, while single quotes (`<< 'EOF'`) are the correct syntax to disable all expansions.

How to eliminate wrong answers

Option A is wrong because `<< EOF` (unquoted delimiter) allows variable expansion and command substitution inside the here-document. Option B is wrong because `<<- EOF` only strips leading tabs from the here-document content but still permits expansion. Option C is wrong because `<< "EOF"` is equivalent to `<< EOF` (double quotes are stripped by the shell), so expansion still occurs.

33
Multi-Selecthard

Which THREE statements are true about the sed command?

Select 3 answers
A.sed 's/old/new/g' file.txt permanently changes the file.
B.sed -i 's/foo/bar/g' file.txt replaces all occurrences of foo with bar in the file.
C.sed uses extended regular expressions by default.
D.sed '/^#/d' file.txt deletes lines that start with #.
E.sed -n '3,5p' file.txt prints lines 3 to 5 of file.txt.
AnswersB, D, E

-i makes in-place changes.

Why this answer

The `-i` flag in sed enables in-place editing, directly modifying the file rather than just outputting changes to stdout. The substitution command `'s/foo/bar/g'` replaces all occurrences of `foo` with `bar` globally on each line, and with `-i`, the changes are written back to the file.

Exam trap

The trap here is that candidates often assume sed always modifies files in place, forgetting that without `-i`, sed only outputs to stdout, and that sed defaults to basic regular expressions, not extended ones.

34
MCQeasy

Refer to the exhibit. An administrator installed a new command in /opt/bin/ but cannot run it without specifying the full path. What is the likely cause?

A.The command is not in the PATH.
B.The command is an alias that conflicts.
C.The command has no execute permission.
D.The command is a function that overrides.
AnswerA

PATH does not include /opt/bin.

Why this answer

The administrator installed the command in /opt/bin/, but the shell cannot find it without the full path because /opt/bin/ is not listed in the PATH environment variable. The PATH variable defines the directories the shell searches for executable commands; if a directory is omitted, commands within it must be invoked with an absolute or relative path.

Exam trap

The trap here is that candidates may confuse a missing PATH entry with a permission issue, but the key clue is that the command runs when the full path is specified, which rules out permission problems and points directly to the PATH variable.

How to eliminate wrong answers

Option B is wrong because an alias conflict would cause the shell to run a different command or produce an error when the alias is defined, but it would not prevent running the command by its full path; the issue here is that the command is not found at all without the full path. Option C is wrong because if the command lacked execute permission, running it with the full path would produce a 'Permission denied' error, not a 'command not found' error; the administrator can run it with the full path, so execute permission is present. Option D is wrong because a function override would replace a command name in the shell session, but the command would still be executable by its full path; the problem is that the shell cannot locate the command in the default search path.

35
MCQhard

A script needs to remove all trailing whitespace (spaces and tabs) from each line of a file. Which sed command will accomplish this?

A.sed 's/[[:space:]]+$//'
B.sed 's/[ \t]*//g'
C.sed 's/^[ \t]*//'
D.sed 's/[ \t]*$//'
AnswerD

Matches trailing spaces/tabs and replaces with nothing.

Why this answer

The sed command 's/[ \t]*$//' uses a regular expression that matches zero or more spaces or tabs (the character class [ \t] followed by *) anchored at the end of the line ($) and replaces them with nothing, effectively removing all trailing whitespace. The * quantifier ensures that both single and multiple trailing whitespace characters are removed, and the $ anchor restricts the match to the end of the line only.

Exam trap

The trap here is that candidates often confuse the quantifiers '*' (zero or more) and '+' (one or more) or forget that sed's default BRE mode requires escaping the '+' quantifier, leading them to choose Option A which would not work as intended.

How to eliminate wrong answers

Option A is wrong because the '+' quantifier is not supported in basic sed (BRE) without escaping; in BRE, '+' is treated as a literal character, so the pattern would not match repeated whitespace. Option B is wrong because the 'g' flag and lack of anchors cause it to remove all whitespace everywhere in the line, not just trailing whitespace. Option C is wrong because the '^' anchor matches the beginning of the line, so it removes leading whitespace instead of trailing whitespace.

36
MCQhard

Refer to the exhibit. An administrator runs this command expecting to capture both stdout and stderr into output.txt. However, the file contains only stdout. What is the error?

A.The file already exists and is not writable.
B.The stdout redirection should be 1> instead of >.
C.The 2>&1 should appear after the > output.txt.
D.The command must be run as root.
AnswerC

Proper order is `> output.txt 2>&1`; then both streams go to the file.

Why this answer

The error is that the `2>&1` redirection appears before the `> output.txt` on the command line. In bash, redirections are evaluated left to right. When `2>&1` is placed first, it redirects stderr (file descriptor 2) to the current target of stdout (file descriptor 1), which at that point is still the terminal, not the file.

The subsequent `> output.txt` redirects only stdout to the file, leaving stderr still going to the terminal. To capture both, `2>&1` must appear after `> output.txt`, so that stderr is redirected to the file descriptor that now points to the file.

Exam trap

The trap here is that candidates often assume the order of redirections doesn't matter, but the shell processes them left to right, so placing `2>&1` before the file redirection causes stderr to be redirected to the terminal instead of the file.

How to eliminate wrong answers

Option A is wrong because if the file already exists and is not writable, the shell would produce an error message (e.g., 'permission denied') and the command would fail entirely, not silently capture only stdout. Option B is wrong because `>` is equivalent to `1>` in bash; both redirect stdout, so using `1>` would not change the behavior. Option D is wrong because root privileges are not required for standard output redirection; any user with write permission on the target directory can redirect output.

37
Multi-Selecteasy

An administrator needs to find files that have been modified within the last 24 hours. Which two parameters are valid for the find command to accomplish this? (Choose TWO)

Select 2 answers
A.-mmin 1440
B.-mtime 0
C.-ctime 0
D.-newer file
E.-atime 1
AnswersA, B

Matches files modified within the last 1440 minutes (24 hours).

Why this answer

`-mmin 1440` matches files whose data modification time is exactly 1440 minutes (24 hours) ago. Option B is correct because `-mtime 0` matches files modified within the last 24 hours (0 days ago). Both parameters target the modification time (`mtime`) and correctly interpret the time range as 'within the last 24 hours'.

Exam trap

The trap here is confusing `-mtime` with `-atime` or `-ctime`, and misunderstanding that `-mtime 0` means 'within the last 24 hours' while `-atime 1` means 'between 24 and 48 hours ago', not 'within the last day'.

38
MCQmedium

In a bash script, a variable 'file' is set to '/var/log/syslog'. Which expansion will yield the string '/var/log'?

A.${file##*/}
B.${file%%/*}
C.${file%/*}
D.${file#*/}
AnswerC

Ly uses ${file%/*} to remove the shortest suffix matching '/*', giving '/var/log'.

Why this answer

The `${file%/*}` expansion uses the `%` operator to remove the shortest suffix matching the pattern `/*`, which matches the last slash and everything after it. Since `file` is `/var/log/syslog`, this removes `/syslog`, leaving `/var/log`. This is a standard parameter expansion in bash for stripping a trailing path component.

Exam trap

The trap here is that candidates often confuse the `%` (remove suffix) and `#` (remove prefix) operators, or mistakenly think `%%` removes the last path component when it actually removes everything from the first slash onward due to longest match behavior.

How to eliminate wrong answers

Option A is wrong because `${file##*/}` uses the `##` operator to remove the longest prefix matching `*/`, which strips everything up to and including the last slash, yielding `syslog` (the filename), not the directory path. Option B is wrong because `${file%%/*}` uses the `%%` operator to remove the longest suffix matching `/*`, which would strip everything from the first slash onward, resulting in an empty string (since the entire string starts with `/`). Option D is wrong because `${file#*/}` uses the `#` operator to remove the shortest prefix matching `*/`, which strips only the first slash and any characters before it, yielding `var/log/syslog` (the path without the leading slash).

39
MCQmedium

A junior system administrator, Sarah, has written a shell script to automate a backup process on a Linux server. The script is located at /home/sarah/backup.sh and has execute permissions. The script contains the line 'mybackup /home/data'. The 'mybackup' command is installed in /usr/local/bin and works correctly when Sarah runs it from her interactive shell. However, when she runs the script using './backup.sh', it fails with the error 'line 5: mybackup: command not found'. Sarah has verified that /usr/local/bin is in her PATH by executing 'echo $PATH' in an interactive session. Which of the following is the most likely cause of this issue?

A.The script uses a different shell interpreter (e.g., /bin/sh instead of /bin/bash) that does not support the command.
B.The script is running in a non-interactive shell that does not source Sarah's .bashrc file, so /usr/local/bin is not in the PATH.
C.The 'mybackup' command is a shell alias, not a real executable.
D.The script does not have the executable bit set.
AnswerB

Non-interactive shells do not source .bashrc, so custom PATH is missing.

Why this answer

When Sarah runs the script with './backup.sh', it starts a new non-interactive shell. Non-interactive shells do not source profile files like .bashrc or .bash_profile, so any PATH modifications made in those files (such as adding /usr/local/bin) are not inherited. Even though Sarah's interactive shell has the correct PATH, the script's shell environment does not, causing the 'mybackup' command not to be found.

Exam trap

The trap here is that candidates assume the PATH seen in an interactive shell is automatically available to all scripts, forgetting that non-interactive shells do not source user profile files.

How to eliminate wrong answers

Option A is wrong because the shell interpreter (e.g., /bin/sh vs /bin/bash) does not affect the availability of external commands like 'mybackup'; the issue is PATH, not shell features. Option C is wrong because if 'mybackup' were a shell alias, it would not be available in non-interactive scripts by default, but the error message 'command not found' indicates the system is looking for an executable, not an alias. Option D is wrong because the question explicitly states the script has execute permissions, so the executable bit is set.

40
MCQmedium

Which command returns the directory part of a full path like '/home/user/script.sh'?

A.echo ${/home/user/script.sh%/*}
B.dirname /home/user/script.sh
C.Either dirname or the expansion ${path%/*} if path is set to the full path
D.basename /home/user/script.sh
AnswerB

Correct. `dirname` is the standard command to return the directory part of a path.

Why this answer

The `dirname` command extracts the directory portion of a full path, returning `/home/user` for the given example. Option B is correct because it directly answers the question—`dirname` is a standard command for this purpose. Option A uses incorrect syntax, Option C describes a parameter expansion (not a command), and Option D (`basename`) returns the filename, not the directory.

Exam trap

The trap is that candidates may think `dirname` is only one of multiple correct answers, but the question explicitly asks for 'which command', making `dirname` the single correct command. Parameter expansions are not commands.

How to eliminate wrong answers

Option A is wrong because the syntax `${/home/user/script.sh%/*}` is invalid; parameter expansion requires a variable name, not a literal string — the correct form would be `${path%/*}` with `path` set to the full path. Option B is wrong because `dirname /home/user/script.sh` is a valid command that returns the directory part, but the question asks for 'which command returns the directory part' and the answer options include a choice that says 'Either dirname or the expansion...' — so B is not wrong per se, but it is incomplete because the expansion also works; the correct answer is the one that acknowledges both methods. Option D is wrong because `basename` returns the filename component (e.g., 'script.sh'), not the directory part.

41
MCQeasy

A user needs to schedule a backup script to run every weekday at 2:00 AM. Which command should they use to set up this recurring job?

A.sleep 3600 && ./backup.sh
B.crontab -e and add a line
C.at -f backup.sh 2:00
D.batch
AnswerB

crontab -e is used for recurring jobs.

Why this answer

The cron daemon is the standard Linux tool for scheduling recurring jobs at specific times. Using `crontab -e` allows the user to edit their personal crontab file and add a line like `0 2 * * 1-5 /path/to/backup.sh` to run the script every weekday (Monday through Friday) at 2:00 AM.

Exam trap

The trap here is that candidates confuse `at` (one‑time scheduling) with `cron` (recurring scheduling), or think `sleep` in a loop can replace cron, but cron is the only correct tool for fixed recurring jobs in Linux.

How to eliminate wrong answers

Option A is wrong because `sleep 3600` only pauses execution for 3600 seconds (1 hour) once; it does not create a recurring schedule and would require manual re‑execution or a loop to repeat. Option C is wrong because `at` is designed for one‑time job scheduling at a specified time, not for recurring daily or weekday jobs. Option D is wrong because `batch` schedules a job to run when system load permits, not at a fixed time, and it also does not support recurring execution.

42
Multi-Selectmedium

Which TWO commands can be used to sort the output of ps -ef by the resident set size (RSS) in descending order?

Select 1 answer
A.ps -ef | sort -k5,5 -rn
B.ps --sort=-rss
C.ps -ef | sort -k3 -rn
D.ps --sort=rss
E.ps -ef | sort -k5 -rn
AnswersB

Correct. `--sort=-rss` sorts by RSS in descending order natively.

Why this answer

Only option B is correct. `ps --sort=-rss` uses the native sorting feature of `ps`, which directly sorts by RSS in descending order (using the minus sign prefix for reverse). Options A and E are incorrect because `ps -ef` does not output RSS; its fields are UID, PID, PPID, C, STIME, TTY, TIME, CMD, so sorting by the 5th field (STIME) does not sort by RSS. Option C sorts by the 3rd field (PPID), not RSS.

Option D sorts by RSS but in ascending order.

Exam trap

The trap here is that candidates often confuse the field number for RSS in `ps -ef` output (it is the 5th field, not the 3rd) and may overlook that `--sort=rss` defaults to ascending order, requiring a minus sign for descending.

43
Multi-Selectmedium

Which TWO of the following are required for a bash script to be executed by the shell (assuming the script is in the current directory)?

Select 2 answers
A.The script must have a shebang (#!) as the first line.
B.The script must not contain any comments.
C.The script must have a .sh extension.
D.The script must be in the PATH environment variable.
E.The script must have execute permission.
AnswersA, E

Required to specify interpreter.

Why this answer

The shebang (#!) as the first line of a bash script tells the kernel which interpreter to use (e.g., #!/bin/bash). Without it, the shell may attempt to execute the script using the default shell (often /bin/sh), which can lead to syntax errors or unexpected behavior. The shebang is essential for explicitly specifying the interpreter, especially when the script uses bash-specific features.

Exam trap

LPI often tests the misconception that a .sh extension is required for shell scripts, but Linux/Unix systems determine executability via the shebang and execute permission, not file extensions.

44
MCQeasy

A user frequently runs 'ls -la' and wants to create an alias 'll' for this command. Which command adds this alias persistently?

A.export ll='ls -la'
B.echo "alias ll='ls -la'" >> ~/.bashrc
C.alias ll='ls -la'
D.alias ll='ls -la' && echo "alias ll='ls -la'" >> ~/.bashrc
AnswerD

Creates the alias immediately and persists it to ~/.bashrc.

Why this answer

It first creates the alias in the current shell session with the `alias` command, then appends the same alias definition to `~/.bashrc` to make it persistent across new shell sessions. The `&&` ensures the second command runs only if the first succeeds, and `~/.bashrc` is the standard file for user-specific Bash aliases that are sourced on interactive shell startup.

Exam trap

The trap here is that candidates often think the `alias` command alone (Option C) is sufficient for persistence, or they confuse `export` with alias creation (Option A), not realizing that `alias` is a shell built-in that only affects the current session and must be added to a startup file to survive reboots.

How to eliminate wrong answers

Option A is wrong because `export` is used to set environment variables, not shell aliases; `export ll='ls -la'` would create an environment variable named `ll` with the value `ls -la`, which is not an alias and will not be expanded by the shell. Option B is wrong because while it correctly appends the alias definition to `~/.bashrc` for persistence, it does not create the alias in the current shell session; the user would need to source the file or run the alias command separately to use `ll` immediately. Option C is wrong because the `alias` command alone creates the alias only for the current shell session; it does not persist across logouts or new terminal windows.

45
MCQeasy

Which command combination will display a sorted list of unique lines from a file?

A.cat file | uniq | sort
B.sort -u file
C.cat file | sort | uniq
D.Both A and C
AnswerC

Correct. By sorting first (`sort`), all duplicates become adjacent, then `uniq` removes them. This guarantees a sorted list of unique lines regardless of the file's initial order.

Why this answer

(cat file | sort | uniq) is the only combination that always produces a sorted list of unique lines. The `sort` command first sorts all lines, making duplicates adjacent, then `uniq` removes those adjacent duplicates, guaranteeing a sorted unique output. Option A (cat file | uniq | sort) may omit non-adjacent duplicates, so it only works if the file is already sorted or duplicates happen to be adjacent.

Option B (sort -u file) is a single command that also produces a sorted unique list, but the question specifically asks for a 'command combination' (i.e., a pipeline of multiple commands), so B is not a valid answer. Option D (Both A and C) is incorrect because A does not always work.

Exam trap

The trap is assuming that `uniq` removes all duplicates. In fact, `uniq` only removes adjacent duplicates. Sorting before `uniq` (option C) is necessary to guarantee complete deduplication.

Candidates may incorrectly think option A works in all cases, or that option D is correct.

How to eliminate wrong answers

Option A is wrong because `cat file | uniq | sort` only removes adjacent duplicates before sorting, so if the file is not already sorted, it will not remove all duplicates; the final sorted list may still contain duplicates. Option B is wrong because `sort -u file` is a single command that directly produces a sorted unique list, but the question asks for a 'command combination' (multiple commands piped together), and option B is a single command, not a combination. Option C is wrong because `cat file | sort | uniq` correctly sorts the file first, then removes all duplicates, producing a sorted unique list; however, the question's correct answer is D (both A and C), so C alone is not the complete answer.

46
MCQeasy

An administrator needs to replace all occurrences of 'old_host' with 'new_host' in the file /etc/hosts. Which sed command should be used?

A.sed -n 's/old_host/new_host/gp' /etc/hosts
B.sed -i 's/old_host/new_host/' /etc/hosts
C.sed -i 's/old_host/new_host/g' /etc/hosts
D.sed 's/old_host/new_host/g' /etc/hosts
AnswerC

Edits /etc/hosts in-place, replacing all occurrences globally.

Why this answer

The `-i` flag enables in-place editing of the file, and the `g` flag (global) ensures all occurrences on each line are replaced, not just the first. The command `sed -i 's/old_host/new_host/g' /etc/hosts` modifies the file directly, replacing every instance of 'old_host' with 'new_host' throughout the file.

Exam trap

The trap here is that candidates often forget the `g` flag for global replacement or omit the `-i` flag for in-place editing, mistakenly thinking sed modifies files by default.

How to eliminate wrong answers

Option A is wrong because the `-n` flag suppresses automatic printing, and `p` prints only lines where a substitution occurred, but without `-i` the file is not modified, so no changes are saved. Option B is wrong because it omits the `g` flag, so only the first occurrence of 'old_host' on each line is replaced, leaving subsequent occurrences unchanged. Option D is wrong because without `-i`, sed writes the modified output to stdout and does not alter the original file /etc/hosts.

47
MCQeasy

A script contains the following line: for i in $(cat file.txt); do echo $i; done. The file file.txt contains a single line with multiple words. How many times will the loop execute?

A.Equal to the number of lines in the file
B.Equal to the number of words in the file
C.Once
D.The loop will not execute
AnswerB

The command substitution splits into words.

Why this answer

The command substitution $(cat file.txt) expands to the content of file.txt, which is a single line with multiple words. The for loop iterates over each word (separated by whitespace) in the expanded string, not over lines. Therefore, the loop executes once per word in the file.

Exam trap

The trap here is that candidates often assume $(cat file.txt) preserves line boundaries, but the for loop splits the output by whitespace, so the number of iterations equals the number of words, not lines.

How to eliminate wrong answers

Option A is wrong because the loop iterates over words, not lines; $(cat file.txt) splits the output by whitespace (default IFS), so the number of iterations equals the number of words, not lines. Option C is wrong because the loop does not execute once; it executes multiple times, once for each word in the single line. Option D is wrong because the loop will execute; file.txt exists and contains data, so the command substitution produces a non-empty string, causing the loop to run.

48
Multi-Selectmedium

Which TWO of the following commands can be used to replace text patterns in a file and output the result?

Select 2 answers
A.awk
B.grep
C.sed
D.tr
E.cut
AnswersA, C

awk can use gsub() or sub() for replacement.

Why this answer

awk is a powerful text-processing tool that can perform pattern matching and replacement using its sub() and gsub() functions, making it suitable for replacing text patterns in a file and outputting the result. It operates on a per-record (line) basis and supports regular expressions, allowing complex substitutions directly within the script.

Exam trap

The trap here is that candidates often confuse grep's pattern-matching capability with text replacement, assuming it can modify content, when in fact grep only filters lines and does not alter or output transformed text.

49
MCQhard

Refer to the exhibit. Why does the cron job fail?

A.The cron job lacks the PATH environment variable.
B.The script is owned by root, but the cron job runs as a different user.
C.The script is not executable.
D.The script lacks a shebang line.
AnswerC

The file permissions do not include execute for the owner.

Why this answer

C is correct because cron jobs require the script to be executable (i.e., have the execute permission bit set). If the script is not executable, cron will fail to run it even if the shebang line and PATH are correct. The error typically appears in the cron log or as a silent failure.

Exam trap

The trap here is that candidates often assume a missing shebang line is the fatal error, but cron actually fails due to the missing execute permission, not the shebang.

How to eliminate wrong answers

Option A is wrong because cron jobs inherit a minimal PATH from the cron daemon, but the PATH variable is not required for a script to run; the script can use absolute paths or set its own PATH. Option B is wrong because cron jobs run as the user who owns the crontab, and the script's ownership does not prevent execution as long as the user has execute permission. Option D is wrong because a shebang line is not strictly required for a script to run; if missing, the script will be executed with the default shell (usually /bin/sh), but the script can still run if it is executable and contains valid shell commands.

50
Multi-Selectmedium

A sysadmin is tasked with configuring the shell environment for all users. Which three files are typically sourced by Bash during login? (Choose THREE)

Select 3 answers
A.~/.bashrc
B./etc/bash.bashrc
C.~/.bash_profile
D./etc/profile
E.~/.profile
AnswersC, D, E

One of the user-specific login files.

Why this answer

During a login shell, Bash reads ~/.bash_profile (if it exists) to set user-specific environment variables and startup scripts. This file is sourced before ~/.profile and is the preferred file for login shell configurations, ensuring environment settings like PATH are applied.

Exam trap

The trap here is that candidates confuse the sourcing order for login shells versus non-login interactive shells, mistakenly selecting ~/.bashrc or /etc/bash.bashrc which are only for non-login shells.

51
MCQeasy

A helpdesk technician receives a call about a user who is unable to run a script that was working yesterday. The user says they only changed the ownership of a file in their home directory. The script is located in /usr/local/bin and is owned by root:root. The script has permissions 755. Which of the following is the most likely cause of the issue?

A.The user changed the ownership of the /usr/local/bin directory.
B.The script requires root privileges to run.
C.The user accidentally changed the ownership of the script file.
D.The user changed the ownership of one of the script's input files, making it unreadable.
AnswerD

If an input file's ownership changed to another user, the current user may lose read access.

Why this answer

The script itself is owned by root:root with 755 permissions, meaning it is executable by everyone. However, if the user changed the ownership of an input file that the script reads, that file may now be owned by the user but with permissions that prevent the script (running as the user) from reading it, or the script may require specific ownership to access the file. Since the script was working yesterday and the only change was ownership of a file in the home directory, the most likely cause is that the script's input file is now unreadable or inaccessible due to the ownership change.

Exam trap

The trap here is that candidates assume the script itself must be the problem because it's in /usr/local/bin, but the question explicitly states the user only changed ownership of a file in their home directory, so the issue must be with a file the script depends on, not the script itself.

How to eliminate wrong answers

Option A is wrong because changing ownership of /usr/local/bin would require root privileges, and the user only changed ownership of a file in their home directory, not a system directory. Option B is wrong because the script has permissions 755 and is owned by root:root, but it does not require root privileges to run; any user can execute it, and it was working yesterday without root. Option C is wrong because the script is located in /usr/local/bin and owned by root:root; the user cannot change ownership of that script without root privileges, and they only changed ownership of a file in their home directory.

52
Multi-Selectmedium

Which THREE of the following commands can be used to transform delimited text (e.g., CSV) by selecting specific fields or columns?

Select 3 answers
A.cut
B.tr
C.awk
D.cat
E.sed
AnswersA, C, E

Selects columns by delimiter.

Why this answer

The `cut` command is specifically designed to extract sections from each line of input, making it ideal for selecting fields from delimited text like CSV. By using the `-d` option to specify a delimiter (e.g., `-d','`) and the `-f` option to choose fields (e.g., `-f1,3`), `cut` can efficiently extract columns without additional processing.

Exam trap

The trap here is that candidates often confuse `cut` with `tr` because both manipulate text, but `tr` operates on characters, not fields, making it unsuitable for column selection.

53
MCQhard

A system administrator is tasked with migrating several shell scripts from a legacy UNIX system to a new Linux server. One script uses the command 'grep -E "pattern1|pattern2"' which works fine on the old system. However, on the new Linux server, the patterns are not being matched correctly. The administrator suspects it is due to differences in grep implementations. Which of the following is the most likely reason for the discrepancy?

A.The old system used GNU grep and the new system uses BSD grep, which treats the -E flag the same.
B.The old system's grep interpreted the pattern as basic regex and the new system's grep interprets it as extended regex because of the -E flag, but the pattern syntax is the same.
C.The pattern includes metacharacters that are interpreted differently because the shell's locale settings are different.
D.The new system's grep does not support the -E flag (e.g., BusyBox grep).
AnswerD

BusyBox grep may not include -E; it only supports basic regular expressions.

Why this answer

BusyBox grep, commonly found in embedded or minimal Linux environments, does not support the -E flag for extended regular expressions. The script uses 'grep -E' with alternation (|), which is an extended regex feature. If the new system runs BusyBox grep, the -E flag is unrecognized, causing grep to interpret the pattern as a basic regex where '|' is treated as a literal character, not an alternation operator, leading to failed matches.

Exam trap

The trap here is that candidates assume all Linux systems use GNU grep and that the -E flag is universally supported, overlooking the existence of BusyBox grep in lightweight distributions, which lacks the -E flag entirely.

How to eliminate wrong answers

Option A is wrong because GNU grep and BSD grep both support the -E flag for extended regex, so the old system using GNU grep and the new system using BSD grep would not cause a discrepancy in pattern matching with -E. Option B is wrong because the -E flag explicitly tells grep to interpret the pattern as extended regex, so both systems would treat it the same; the issue is not about basic vs. extended regex interpretation but about whether the -E flag is supported at all. Option C is wrong because locale settings affect character classes and collation, not the fundamental interpretation of the alternation metacharacter '|' in extended regex; the shell's locale would not cause the pattern to fail matching entirely.

54
Multi-Selectmedium

Which THREE of the following are types of expansion performed by the bash shell during command parsing?

Select 3 answers
A.Parameter expansion
B.Tilde expansion
C.Brace expansion
D.Variable assignment
E.Alias expansion
AnswersA, B, C

e.g., ${var} expands variable value.

Why this answer

Parameter expansion (e.g., ${var}, $var) is a fundamental expansion step performed by the bash shell during command parsing, where variables are replaced with their values before execution. This occurs after brace expansion and tilde expansion but before word splitting and pathname expansion, as defined in the bash manual's expansion order.

Exam trap

The trap here is that candidates may confuse alias expansion (which occurs during tokenization) with the formal expansion phases listed in the bash manual, or mistake variable assignment as an expansion type when it is actually a separate parsing step.

55
Multi-Selecthard

Which TWO commands can be used to count the number of lines in a file named 'data.txt'?

Select 2 answers
A.wc -l data.txt
B.awk 'END{print NR}' data.txt
C.cat data.txt | wc -c
D.grep -c '.*' data.txt
E.sed -n '$=' data.txt
AnswersA, B

wc -l counts line endings.

Why this answer

`wc -l` specifically counts the number of newline characters in the file, which corresponds to the number of lines. Option B is correct because `awk 'END{print NR}'` processes the file line by line, and the built-in variable `NR` holds the total number of records (lines) processed when the END block is executed, thus outputting the line count.

Exam trap

The trap here is that candidates often confuse `wc -c` (byte count) with `wc -l` (line count), or assume `grep -c '.*'` counts all lines without realizing it may miss empty lines or behave differently across grep implementations.

56
MCQeasy

Which shell loop is most appropriate for iterating over all files in a directory, performing an action only on regular files, while safely handling filenames with spaces?

A.for file in "`ls`"; do ...
B.for file in `ls`; do if [ -f $file ]; then ... ; done
C.for file in $(ls); do if [ -f "$file" ]; then ... ; done
D.for file in *; do if [ -f "$file" ]; then ... ; done
AnswerD

Correctly handles spaces and regular files.

Why this answer

It uses a glob pattern (*) to iterate over all files in the current directory, which is safe for filenames with spaces. The double quotes around "$file" in the test condition [ -f "$file" ] ensure that filenames containing spaces or special characters are handled as a single argument, preventing word splitting. This approach avoids parsing the output of ls, which is unreliable and can break with unusual filenames.

Exam trap

The trap here is that candidates often assume ls output is safe for iteration, but the shell's word splitting and globbing on unquoted command substitutions cause failures with spaces, making the glob pattern the only reliable method.

How to eliminate wrong answers

Option A is wrong because it uses ls output inside double quotes, which treats the entire output as a single string, so the loop runs only once with all filenames concatenated, not iterating over individual files. Option B is wrong because it uses backticks without quotes around the ls command, causing word splitting that breaks filenames with spaces into separate loop iterations, and also lacks quotes around $file in the test, leading to errors with spaces. Option C is wrong because $(ls) is subject to word splitting and pathname expansion, so filenames with spaces are split into multiple arguments, and the loop may also expand glob characters in filenames, causing incorrect behavior.

57
MCQeasy

Refer to the exhibit. When will the cron job execute?

A.Every minute of every hour, but only weekdays.
B.Every day at midnight.
C.Every minute.
D.Every hour.
AnswerC

Five asterisks mean every minute of every hour of every day.

Why this answer

The cron job entry `* * * * *` specifies five fields (minute, hour, day of month, month, day of week), each set to `*`, meaning 'every'. This results in the job executing every minute of every hour, every day of the month, every month, and every day of the week — i.e., every minute without restriction.

Exam trap

The trap here is that candidates often misinterpret `* * * * *` as 'every hour' or 'every day at midnight' because they focus on the asterisks without understanding that each field must be evaluated independently — every asterisk means 'every possible value' for that field, leading to execution every minute.

How to eliminate wrong answers

Option A is wrong because 'every minute of every hour, but only weekdays' would require the day-of-week field to be set to 1-5 (or MON-FRI), not `*`. Option B is wrong because 'every day at midnight' would require the minute and hour fields to be `0 0`, not `* *`. Option D is wrong because 'every hour' would require the minute field to be a specific value (e.g., `0`) and the hour field to be `*`, but here both minute and hour are `*`, which means every minute, not just every hour.

Ready to test yourself?

Try a timed practice session using only Shells, Scripting and Data Management questions.