Courseiva

CCNA Shells Scripting Questions

44 questions · Shells Scripting topic · 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

Unquoted command substitution splits on IFS whitespace, so 'John Doe, 123 Main St' fragments into separate words rather than one record. A while loop with IFS= and read -r preserves each line intact, correctly handling embedded spaces and commas in the CSV.

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

A Linux administrator needs to extract all lines from `/var/log/syslog` that contain the word `error` (case-insensitive) and save them to `errors.txt`. Which command accomplishes this?

A.grep -c error /var/log/syslog > errors.txt
B.grep -i error /var/log/syslog > errors.txt
C.grep -v error /var/log/syslog > errors.txt
D.grep -l error /var/log/syslog > errors.txt
AnswerB

The -i option makes grep ignore case, so it matches error, Error, ERROR, and so on. The redirection operator > sends the matching lines to errors.txt. This is the standard and correct way to perform a case-insensitive search and save the results to a file.

Why this answer

The grep command with -i performs a case-insensitive search, and the > redirection writes the matching lines to a file. The other options either invert the match, count matches, or list filenames, none of which produce the desired output of the matching lines themselves.

Exam trap

The trap here is confusing grep options that alter output format with options that filter content, such as using -c or -l when the actual lines are needed.

3
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

Windows-style CRLF endings leave a trailing carriage return on the shebang line, so the kernel seeks an interpreter named `/bin/bash\r`, which does not exist, producing the bad interpreter error. Converting the file with `dos2unix` or `sed` restores Unix LF endings and the script runs.

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.

4
MCQhard

A system administrator runs a script that contains the line: trap 'echo "Cleaning up..."' EXIT. The script is executed and then receives SIGINT (Ctrl+C) before normal completion. What happens?

A.The trap on EXIT is ignored because the script was interrupted by a signal.
B.The trap on EXIT is executed because SIGINT causes the shell to exit.
C.The trap on EXIT is executed only if the script completes normally.
D.The script continues running because SIGINT is trapped and ignored by default.
AnswerB

When a script receives SIGINT, the default action terminates the shell. Because the EXIT trap is set, the shell runs the trap command just before it exits, regardless of the reason for termination. The echo is therefore executed during the SIGINT-triggered exit, matching the described behavior.

Why this answer

The EXIT trap runs when the shell exits, regardless of whether the exit is normal or caused by a signal that terminates the shell. When SIGINT is received and not otherwise trapped, the shell exits, triggering the EXIT trap before termination. This makes EXIT suitable for cleanup actions such as removing temporary files.

Exam trap

The trap here is believing that an EXIT trap only fires on successful completion, when in fact it also runs when the shell is terminated by a signal.

5
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 handles quoted fields via FPAT or custom field-separator logic, and csvkit implements RFC 4180 quoting rules, so embedded commas inside quotes are not treated as delimiters. Simple cut or IFS-based splitting cannot distinguish quoted commas, so a quote-aware parser is required.

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.

6
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

`wait` with no arguments blocks the calling shell until every background job it spawned has terminated, then returns. This directly satisfies the stem's requirement to pause the script until all background processes finish, unlike `sleep` or polling loops that cannot detect job completion.

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.

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` follows the file as new lines are appended, satisfying the real-time monitoring constraint, while the pipe feeds each line to `grep 'ERROR'` for filtering. The redirection then writes only matching lines to error.log. Unlike `cat`, which exits at EOF, `tail -f` persists, so continuous logging is captured.

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
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

unset removes a variable or array from the current shell environment. Applying it to BASH_ALIASES clears the associative array, satisfying the stem's requirement to unset it. The command takes the variable name without a dollar sign.

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.

9
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

`grep -v` inverts the match, printing only lines that fail the pattern test, so every line lacking "error" is emitted while matching lines are suppressed. This directly satisfies the stem's requirement to display non-matching lines from /var/log/syslog, with the file passed as grep's final operand.

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.

10
MCQhard

A shell script contains the following line: `find /data -type f -name '*.tmp' -exec rm {} \;`. What is the effect of this command?

A.It removes all empty directories ending with .tmp in /data.
B.It lists all .tmp files in /data without deleting them.
C.It removes all files ending with .tmp in /data and its subdirectories.
D.It removes all files in /data that do not end with .tmp.
AnswerC

The find command searches /data for regular files (-type f) with names ending in .tmp. The -exec rm {} \; executes the rm command on each found file, removing it. The backslash before the semicolon escapes it so that the shell passes the semicolon to find, which uses it to terminate the command. This effectively deletes all .tmp files under /data, including subdirectories.

Why this answer

The find command with -type f -name '*.tmp' -exec rm {} \; locates all regular files with names ending in .tmp under /data and executes rm on each. This deletes those files. The backslash escapes the semicolon to prevent shell interpretation.

This is a common idiom for batch deletion. Other options misinterpret the type, name pattern, or action.

Exam trap

The trap here is misunderstanding the -exec action or the -name pattern, leading to thinking it lists files or affects different files.

11
MCQmedium

A shell script must exit immediately with a non-zero status if any command fails, and it must also treat an unset variable as an error. Which line should be placed at the top of the script?

A.set -e -u
B.set -u -x
C.set -o errexit -o nounset -o xtrace
D.set -e -x
AnswerA

The -e option makes the shell exit as soon as a command returns non-zero, and -u makes referencing an unset variable an error that triggers that exit. Together they satisfy both stated requirements in a single line. This combination is the conventional safety header for scripts that must fail fast rather than continue with bad state.

Why this answer

The fail-fast requirement maps to errexit (-e) and the unset-variable requirement maps to nounset (-u), so 'set -e -u' is the precise answer. Adding xtrace brings noisy tracing that was not asked for, and omitting either -e or -u leaves one requirement unmet. Short option letters and their long -o equivalents name the same behaviours, so the combined short form is the cleanest expression.

Exam trap

The trap here is assuming that -x and -u are interchangeable safety options, when -x only traces commands and provides no error handling at all.

12
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.

13
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

Cron executes jobs with a minimal environment, so PATH typically omits directories available in an interactive shell. Commands resolving manually then fail under cron because the binary cannot be located, unless absolute paths or an explicit PATH are set.

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.

14
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

`set -e` makes the shell exit immediately when any command returns a non-zero status, satisfying the fail-fast requirement. `set -x` enables tracing, printing each command with its expanded arguments to stderr before execution. Combined as `set -ex`, both constraints in the stem are met within a single statement.

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.

15
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

The sed substitute command s/foo/bar/ replaces only the first match per line by default; the g flag is what makes it global. Applied to each line of the file, this expression swaps the initial 'foo' with 'bar' and leaves any later occurrences on that line untouched.

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.

16
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

grep -v inverts the match, printing every line that does not contain the pattern 'ERROR'. The pattern is treated as a basic regular expression, and unmatched lines pass through unchanged, which directly satisfies the requirement to list all non-matching lines from the log file.

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.

17
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

Apache holds the original file descriptor after logrotate renames access_log, so it keeps writing to the renamed inode (access_log.1). Sending USR1 or HUP triggers Apache to close and reopen its log files, binding them to the newly created access_log.

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.

18
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

The -print0 flag terminates each path with a NUL byte, and xargs -0 reads that delimiter, so filenames containing spaces or special characters are passed to rm intact rather than being split into separate arguments.

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.

19
MCQhard

A shell script contains a function named `cleanup` that must run automatically when the script exits, whether it finishes normally or is terminated by a signal. Which construct should be used to register this function?

A.cleanup && exit
B.trap cleanup EXIT
C.trap cleanup INT TERM
D.at_exit cleanup
AnswerB

The `trap` builtin with the EXIT pseudo-signal arranges for the named command or function to run when the shell exits, including normal completion and exits triggered by signals that the shell handles. Registering `cleanup` this way ensures the function executes in both scenarios described, making it the correct construct.

Why this answer

The `trap ... EXIT` form registers a handler for the shell's exit event, which fires on normal termination as well as on exits caused by signals the shell processes. That covers both cases in the scenario, whereas trapping only specific signals would miss normal completion and merely calling the function would not defer it.

Exam trap

The trap here is assuming that trapping INT and TERM also covers normal exit; only the EXIT pseudo-signal fires on ordinary script completion.

20
MCQmedium

A script needs to read a file line by line, preserving leading and trailing whitespace and backslashes. Which loop construct should be used?

A.while IFS= read -r line; do echo "$line"; done < file.txt
B.while read line; do echo "$line"; done < file.txt
C.while read -r line; do echo "$line"; done < file.txt
D.for line in $(cat file.txt); do echo "$line"; done
AnswerA

Setting IFS to an empty value prevents read from trimming leading and trailing whitespace, and the -r option disables backslash escape processing. Together they preserve the line exactly as it appears in the file, satisfying the requirement to keep whitespace and backslashes intact during iteration.

Why this answer

Reading a file line by line while preserving exact content requires disabling both word splitting and backslash processing. Clearing IFS stops the shell from trimming leading and trailing whitespace, and the -r option stops backslash escapes from being interpreted. Using only one of these settings leaves the other behavior active and alters the data.

Exam trap

The trap here is assuming that the -r option alone preserves all characters, overlooking that IFS still causes leading and trailing whitespace to be stripped.

21
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

Option C is correct because the dot command (.) is the POSIX-standard abbreviation for source, so `source file` and `. file` are equivalent in bash. Option D is correct because source reads and executes the script's commands in the current shell environment, which is why variables and functions defined in the sourced file persist in the calling shell. Option A is wrong because executing in a subshell is what happens when you run a script normally (e.g., `bash script.sh` or `./script.sh`), not when sourcing it.

Option B is wrong because the dot form is specified by POSIX and works in POSIX sh, even though the name `source` itself is a bash extension. Option E is wrong because source reads the file with the shell, so the script only needs read permission, not execute permission.

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.

22
MCQmedium

A script uses the command substitution: files=$(ls). Which statement about the resulting value of files is true?

A.The variable files contains the output of ls with newlines replaced by spaces.
B.The variable files contains the exit status of the ls command.
C.The variable files contains the output of ls, with trailing newlines removed.
D.The variable files contains a list of filenames separated by null characters.
AnswerC

Command substitution captures the standard output of the command and strips any trailing newline characters. Internal newlines remain, but the final newline that ls typically outputs is removed. Therefore the variable holds the output with trailing newlines stripped, which is the documented behavior.

Why this answer

Command substitution captures the standard output of the enclosed command and removes trailing newline characters. Internal newlines are retained, but the final newline is stripped. This behavior is consistent across shells and is why using the result unquoted can lead to word splitting on spaces, tabs, and newlines.

Exam trap

The trap here is thinking that command substitution replaces all newlines with spaces or that it captures the exit status rather than the command's output.

23
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 perform command substitution in Bash, executing the enclosed command and assigning its standard output to the variable. This is a valid capture method, equivalent in effect to the modern $(command) syntax, and works in all POSIX-compliant shells.

Why this answer

Option A, var=`command`, is correct because backticks are the legacy command-substitution syntax in Bash: the shell runs command in a subshell and replaces the backtick expression with its standard output, which is then assigned to var. Option C, var=$(command), is correct because the modern $(...) form performs the same command substitution, capturing command's stdout into var, and is preferred since it nests more cleanly and avoids backtick escaping issues. Option B, var={command}, is not valid because braces are used for brace expansion (e.g., {a,b}) and parameter expansion (${var}), not command substitution.

Option D, var|command, is not valid because it would attempt to pipe the variable name as a command into another command rather than assign output. Option E, var=command, is not valid because it simply assigns the literal string 'command' to var without executing it or capturing any output.

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.

24
MCQeasy

A user runs the command `echo $HOME` in a Bash shell and receives the output `/home/alice`. A colleague later runs the same command in a different shell and gets `/root`. Which type of shell variable is being displayed?

A.A local shell variable
B.An environment variable
C.A special shell parameter
D.A positional parameter
AnswerB

HOME is an environment variable that is exported to child processes. It is set by the login process and reflects the home directory of the user who started the shell. Because it is inherited, a different user or a shell started with a different effective user will show a different value, which explains the observed difference.

Why this answer

HOME is an environment variable that is exported to child processes, so it is inherited by commands run from the shell. It is set at login time based on the user account, which is why different users see different values. Local variables, positional parameters, and special parameters do not behave this way.

Exam trap

The trap here is assuming that any variable set in a shell is automatically an environment variable, when many variables remain local unless exported.

25
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

-F: sets the input field separator to a colon, so each line splits into name, age and department. The print statement outputs $1 and $3 separated by awk's default output separator, a single space, producing the required name and department pair.

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.

26
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

`set +e` disables the errexit behaviour, so bash continues running subsequent commands after any individual command returns a non-zero exit status. This directly satisfies the stem's requirement that the script keeps executing despite failures, since errexit is off by default but may have been enabled by a prior `set -e`.

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.

27
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.

28
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

${var-default} substitutes the default only when var is unset, whereas ${var:-default} also substitutes when var is set but empty. Using the single-colon-less form satisfies the stem's requirement that the default apply solely to unset variables, preserving intentional empty values.

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.

29
MCQmedium

A junior administrator needs to extract only the lines containing the word 'ERROR' from /var/log/syslog, but the log may have inconsistent casing (e.g., 'ERROR', 'Error', 'error'). Which command will print all such lines while ignoring case?

A.grep -v 'ERROR' /var/log/syslog
B.grep -i 'ERROR' /var/log/syslog
C.grep 'ERROR' /var/log/syslog
D.grep -c 'ERROR' /var/log/syslog
AnswerB

The -i option makes grep perform a case-insensitive match, so it will match 'ERROR', 'Error', 'error', and any other casing. This directly satisfies the requirement to catch inconsistent casing without needing multiple patterns or preprocessing. Other options either do not ignore case or misinterpret the pattern.

Why this answer

To extract lines with any casing of 'ERROR', the case-insensitive option -i must be used with grep. This allows matching 'ERROR', 'Error', 'error', etc., in a single command. The other grep invocations either do not ignore case, invert the match, or count lines instead of displaying them, so they fail to meet the scenario's need.

Exam trap

The trap here is assuming that grep is case-insensitive by default or that a simple pattern without flags will catch all casings.

30
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

The `-i` flag edits file.txt in place, so no redirection or temporary file is needed. Combined with the `g` substitution flag, sed replaces every occurrence of foo on each matched line, not merely the first. This satisfies the requirement of replacing all occurrences directly within the file.

Why this answer

Option B is correct because the -i flag enables in-place editing, so sed -i 's/foo/bar/g' file.txt rewrites file.txt directly, replacing every occurrence of foo with bar due to the g (global) flag. Option D is correct because the address /^#/ matches lines beginning with # and the d command deletes them, so sed '/^#/d' file.txt removes comment lines from the output. Option E is correct because -n suppresses default output and the address range 3,5 with the p command prints only lines 3 through 5.

Option A is wrong because without -i sed writes results to stdout, leaving file.txt unchanged. Option C is wrong because sed uses basic regular expressions by default; extended regex requires the -E or -r option.

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.

31
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

The shell searches only directories listed in PATH when resolving bare command names. Since /opt/bin is absent from PATH, the binary is unfindable without its full path. Adding that directory to PATH restores normal lookup.

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.

32
Multi-Selectmedium

A user needs to find all lines in a file that contain the word `error` while ignoring case, and also print the line number for each match. Which TWO `grep` invocations accomplish this? (Choose two.)

Select 2 answers
A.grep -l -i error file.log
B.grep -c -n error file.log
C.grep -in error file.log
D.grep -v -n error file.log
E.grep -i -n error file.log
AnswersC, E

The `-i` option makes matching case-insensitive, and `-n` prefixes each matching line with its line number. Combined in `-in`, both requirements are met in a single concise invocation. This is the conventional short-option form and works on all POSIX-compatible grep implementations.

Why this answer

Case-insensitive matching is enabled by `-i`, and line numbers are added by `-n`. Whether written as `-in` or as separate `-i -n` options, both forms satisfy the requirement to list matching lines with their line numbers. The other options invert the match, print only a count, or print only filenames, none of which meets the stated goal.

Exam trap

The trap here is that `-c` and `-l` look like they add useful information, but they replace the normal matching-line output instead of supplementing it.

33
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

Redirection order determines descriptor duplication: writing 2>&1 before > output.txt duplicates stderr onto the terminal's stdout, which the later redirection does not inherit. Placing 2>&1 after > output.txt makes stderr point at the file, satisfying the stem's requirement to capture both streams.

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.

34
MCQeasy

A user wants to view the first 10 lines of a log file named /var/log/syslog. Which command should they use?

A.tail /var/log/syslog
B.cat /var/log/syslog | more
C.head /var/log/syslog
D.less /var/log/syslog
AnswerC

The head command by default displays the first 10 lines of a file. This is exactly what the user needs. It is a simple and efficient way to peek at the beginning of a file without loading the entire file into memory. This command is part of coreutils and is commonly used in shell scripting and daily administration for quickly inspecting file contents.

Why this answer

The head command is designed to output the first part of files, with a default of 10 lines. It is the correct choice for viewing the first 10 lines of a log file. The tail command shows the last lines, while cat and less display the entire file or allow interactive viewing without limiting to the first 10 lines.

This is a basic file inspection task in Linux.

Exam trap

The trap here is confusing head and tail, or thinking that a pager like less automatically limits output to the first 10 lines.

35
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).

36
MCQmedium

A backup script stores its log file path in the variable LOGFILE and needs to append a timestamp line to that file. Which command correctly appends the output of the `date` command to the file named in the variable?

A.date >> $LOGFILE
B.date < $LOGFILE
C.date | $LOGFILE
D.date > $LOGFILE
AnswerA

The `>>` operator opens the file in append mode, adding the output of `date` to the end without erasing existing content. Because `$LOGFILE` expands to the stored path, the timestamp is appended to the intended log file. This satisfies the requirement of preserving prior log entries.

Why this answer

Appending output requires the `>>` redirection operator, which opens the destination file for appending rather than truncating it. With the variable expanded to the log path, `date >> $LOGFILE` adds a new timestamp line while keeping all previous entries intact, which is exactly what the backup script needs.

Exam trap

The trap here is confusing `>` with `>>`; the single greater-than sign overwrites the file, silently destroying existing log data.

37
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 opens the user's crontab for editing, where a schedule such as 0 2 * * 1-5 runs the backup script at 02:00 Monday through Friday. This satisfies the weekday-only, recurring requirement, unlike at or systemd timers for one-off 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.

38
MCQeasy

A user wants to set a shell variable named DEPLOY_ENV to the value 'staging' in the current Bash session so that child processes can read it. Which command accomplishes this?

A.DEPLOY_ENV=staging
B.set DEPLOY_ENV=staging
C.export DEPLOY_ENV=staging
D.env DEPLOY_ENV=staging
AnswerC

The export builtin marks the variable for inclusion in the environment of subsequently executed commands. Combining assignment and export in one statement sets the value and makes it available to child processes, exactly matching the scenario's requirement that child processes can read DEPLOY_ENV in the current session.

Why this answer

To make a variable available to child processes, it must be exported into the environment. The export builtin, used together with an assignment, both sets the variable in the current shell and ensures it is inherited by subsequently launched commands. A plain assignment stays local to the shell, set controls shell options, and env without a command only displays the environment.

Exam trap

The trap here is confusing a shell variable with an environment variable and assuming that any assignment automatically makes the value available to child processes.

39
MCQhard

An administrator needs to extract only the fifth field from a colon-delimited file, but some lines contain fewer than five fields and must be skipped rather than printed as empty. Which awk program accomplishes this?

A.awk -F: '$5 != "" {print $5}' file
B.awk -F: '{print $5}' file | grep -v '^$'
C.awk -F: 'length($5) > 0 {print $5}' file
D.awk -F: 'NF >= 5 {print $5}' file
AnswerD

NF holds the number of fields on the current record, so NF >= 5 selects only lines that actually contain at least five colon-separated fields, and print $5 emits the fifth one. Lines with fewer fields are never printed, exactly matching the requirement to skip short lines rather than emit empty output. This is the idiomatic awk approach.

Why this answer

The requirement is to skip records that lack a fifth field, which is exactly what the NF field-count variable expresses. Testing NF >= 5 before printing $5 rejects short lines at the source, whereas tests on the value or length of $5 conflate an absent field with a present-but-empty one and can silently drop legitimate empty fields. Using NF keeps the decision tied to the record's structure.

Exam trap

The trap here is testing whether $5 is empty instead of testing NF, which cannot distinguish a missing field from a field that exists but contains no characters.

40
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

The `-i` flag edits /etc/hosts in place, satisfying the requirement to replace all occurrences without redirecting to a temporary file. The `g` suffix applies the substitution globally across every match on each line, not merely the first, so multiple instances of 'old_host' are all rewritten to 'new_host'.

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.

41
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

Command substitution splits on IFS whitespace, so each word from the single line becomes a separate argument to `for`. The loop therefore iterates once per word, satisfying the stem's constraint of one line containing multiple words. Word count, not line count, determines execution.

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.

42
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 processes input line by line, and its gsub() function substitutes every match of a pattern within a field or record, writing the modified text to standard output. This satisfies the requirement to replace text patterns and output the result without altering the source file.

Why this answer

Option A, awk, is correct because awk is a full text-processing language that supports substitution via the gsub() function (e.g., awk '{gsub(/old/,"new"); print}' file), which replaces matching patterns and prints the modified result to standard output. Option C, sed, is correct because sed is the classic stream editor whose s/// substitution command (e.g., sed 's/old/new/g' file) replaces text patterns and writes the transformed content to stdout without altering the original file. Option B, grep, is not correct because grep only searches for and prints lines matching a pattern; it does not replace text.

Option D, tr, is not correct because tr translates or deletes individual characters rather than replacing multi-character text patterns. Option E, cut, is not correct because cut extracts selected fields or columns from each line and performs no substitution.

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.

43
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

Parameter expansion substitutes a variable's value, such as $HOME or ${name}, into the command line before execution. Bash performs it during word splitting and expansion, making it one of the shell's documented expansion types alongside tilde, brace, command and arithmetic expansion.

Why this answer

Parameter expansion (A) is a genuine bash expansion type: the shell replaces constructs like $var, ${var}, or ${var:-default} with their values during command parsing. Tilde expansion (B) is also a real expansion: a leading ~ is replaced with the current user's home directory (or ~user with that user's home), as in ~/file becoming /home/user/file. Brace expansion (C) is likewise a bash expansion type: patterns such as {a,b,c} or {1..5} are expanded into multiple words before other expansions like parameter and command substitution.

Variable assignment (D) is not an expansion but a shell operation that stores a value in a variable, and alias expansion (E) is not one of bash's documented expansion stages; aliases are substituted earlier during tokenization/alias lookup, not as a formal expansion type.

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.

44
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

The schedule field of five asterisks matches every minute of every hour, day and month, so cron launches the job once per minute. Each asterisk means the full range for that field, giving the highest possible frequency.

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 questions.