CCNA Shells Scripting Questions

57 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

Reads each line correctly with IFS= to preserve whitespace.

Why this answer

Option A is correct: using a while loop with read -r processes each line correctly, preserving whitespace. Option B treats the entire file as one string. Option C still uses command substitution which splits on whitespace.

Option D xargs by default splits on whitespace and is not designed for line-by-line processing of CSV.

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 indicates that the shell encountered a carriage return character interpreted as a command, which happens when the script uses Windows line endings (CRLF). Options B, C, and D are less likely.

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

Option C is correct because awk with FPAT or dedicated tools can handle quoted commas properly.

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

Option C is correct because 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

Option C is correct. The wait command with no arguments waits for all background jobs to finish. Option A only waits for job 1.

Option B sleeps a fixed time. Option D lists jobs but does not wait.

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

Options C and D are correct. The while-read loop with NUL delimiter (C) safely handles any filename. The find -exec (D) processes each file separately without word splitting.

Options A and E are unsafe due to word splitting. Option B expands to a single literal asterisk.

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

Option A is correct: tail -f follows the file and grep filters lines. Option B uses cat which does not monitor live. Option C is a pager.

Option D is a text editor.

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

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

Option A is correct. The unset command without any options removes a variable or array. `unset BASH_ALIASES` will unset the variable. Options B and C are not valid syntax for unsetting.

Option D is not a valid 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

Option B is correct because if the while loop is part of a pipeline, it runs in a subshell and variable changes are not visible to the parent.

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

Option B is correct because grep -v inverts the match, showing only lines that do not contain the pattern. The -i option in A would ignore case but still show matching lines. Options C and D do not invert the match.

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

Option D is correct. First extract the IP field with awk, sort, then count duplicates with uniq -c, and finally sort numerically in reverse to show most frequent first.

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

Option D is correct because find executes both chown and chmod on each .txt file, changing group via :developers and setting permissions to 640.

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

Option B is correct. The policy defines an allow rule for /usr/bin/* and a specific deny rule for /usr/bin/passwd. Typically, deny rules override allow rules when both match, so the execution is denied.

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

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

Option A is correct because `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

Option D is correct because 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

Option C is correct because the -v option in grep inverts the match, showing lines that do not contain ERROR. Option A shows lines containing ERROR. Option B is also -v? Wait, we moved correct to C.

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 correct answer is A. After log rotation, Apache continues writing to the old inode unless signaled to reopen. A postrotate script sending USR1 or HUP is the standard solution.

Option B (copytruncate) is alternative but less reliable; options C and D are ineffective.

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

Option B is correct because -print0 and xargs -0 handle special characters by using null delimiters. Option A is unsafe due to word splitting. Options C and D do not use xargs.

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

Option C is correct because 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

The correct answers are A and B. $(...) and backticks are both valid command substitution syntax. Options C, D, and E are not valid.

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

Option A is correct. trap with signal name SIGTERM (or number 15) runs the clean-up function when the signal is received. Options B and C use wrong syntax or signal. Option D uses EXIT, which runs on script exit from any cause.

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

Option A is correct because 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

Option A is correct because `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.
AnswerA

Each line prints the first two fields separated by space.

Why this answer

Option C is correct because each line is split into three fields; only field1 and field2 are echoed, resulting in 'a b' and 'd e' on separate lines.

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

Option B is correct because it uses process substitution to tee each stream to both a file and the terminal. The 2>&1 in other options merges stderr into stdout, which is not desired.

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

Option B is correct: ${var-default} expands to default only if var is unset, while ${var:-default} also expands to default if var is empty. Option A is wrong because it also handles empty. Option C assigns the default to the variable.

Option D prints an error and exits.

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 is misspelled.
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.
AnswerB

The correct directive is 'notifempty', not 'notifempty'.

Why this answer

Option B is correct because the 'notifempty' directive is misspelled as 'notifempty' (it should be 'notifempty'). Logrotate silently ignores unknown directives, so the misspelled directive has no effect. Without the correct 'notifempty' directive, logrotate will skip rotation if the log file is empty, which can prevent rotation from occurring automatically even though the manual forced rotation with -f succeeds.

Exam trap

The trap here is that candidates assume a forced rotation with -f works the same as automatic rotation, but -f overrides conditions like empty files, whereas automatic rotation respects the 'notifempty' directive (or its absence).

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

Option D is correct because 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

Option B is correct because 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

Option B is correct because the PATH does not include /opt/bin, so the command is not found unless full path is given.

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

Option A is correct: sed 's/[ \t]*$//' uses a regular expression to match zero or more spaces/tabs at the end of line. Option B removes leading whitespace. Option C removes all whitespace globally.

Option D uses + quantifier without -E flag, which is not valid in basic regular expressions.

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

Option B is correct. In the command `command 2>&1 > output.txt`, the redirection order causes stderr to be redirected to the current stdout (terminal) before stdout is redirected to the file. Thus only stdout goes to the file, and stderr remains on the terminal.

The correct order is `command > output.txt 2>&1`.

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

Option A is correct because `-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

Removes the shortest suffix matching /*, yielding /var/log.

Why this answer

Option C is correct because 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

Option B is correct. When a script runs, it starts a non-interactive shell that does not source the user's .bashrc or .profile, so custom PATH additions are not inherited. Option A would cause 'Permission denied'.

Option C: aliases are not expanded in non-interactive shells, but the command is a real executable. Option D: the shebang line determines the interpreter; if /bin/sh is used, it may still have the same PATH issue, but the most direct cause is missing PATH.

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
AnswerC

Both return /home/user.

Why this answer

Option C is correct because both `dirname` and the shell parameter expansion `${path%/*}` extract the directory portion of a given path. The `dirname` command is a standard utility that strips the last component and trailing slash, returning the parent directory. The `${path%/*}` expansion uses the `%` operator to remove the shortest suffix matching `/*`, which effectively removes the filename and leaves the directory path.

This works only if `path` is a variable containing the full path string.

Exam trap

The trap here is that candidates often pick only `dirname` (Option B) because it is the obvious command, missing that the shell parameter expansion `${path%/*}` is also a valid and commonly used method, and that the question explicitly asks for 'which command' in a way that expects recognition of both approaches as correct.

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

Option B is correct because crontab -e is used to edit the personal crontab file for recurring jobs. Option A is wrong because at is for one-time scheduling. Option C is wrong because sleep only delays execution.

Option D is wrong because batch runs when the system load is low.

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 2 answers
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, E

--sort=-rss sorts by RSS descending.

Why this answer

Option B is correct because `ps --sort=-rss` directly sorts the process list by resident set size (RSS) in descending order, using the minus sign prefix to indicate reverse sort. This is a native `ps` feature that avoids piping to `sort`, which can be less reliable due to column alignment issues.

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

Option A is correct because 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

Option C is correct because it both creates the alias in the current session and appends it to ~/.bashrc so it persists across sessions. Option A only creates a temporary alias. Option B adds to the file but does not activate it immediately.

Option D exports a variable, not an alias.

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
AnswerD

Both methods yield sorted unique lines.

Why this answer

Option D is correct because both A and C produce a sorted list of unique lines from a file. In option A, `cat file | uniq | sort` first removes adjacent duplicates with `uniq`, then sorts the remaining lines, which yields a sorted unique list only if the file was already sorted. In option C, `cat file | sort | uniq` sorts the file first, then removes all duplicate lines (adjacent after sorting), guaranteeing a sorted unique list.

Option B (`sort -u file`) also produces a sorted unique list, but it is not part of the combination asked for in the question.

Exam trap

The trap here is that candidates often assume `uniq` alone removes all duplicates, forgetting that it only works on adjacent lines, leading them to pick option A as correct without realizing the sorting order matters.

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

Option D is correct because sed -i edits the file in-place with global substitution. Without -i, changes are only displayed on stdout. Without the g flag, only the first occurrence per line is replaced.

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

Options A and B are correct: sed and awk both support search and replace operations. Option C (grep) only searches, Option D (cut) extracts columns, Option E (tr) translates characters.

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

Option C is correct because 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

Option D is correct because 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

Option A is correct: The new system may have a minimal grep implementation (e.g., from BusyBox) that does not support the -E flag for extended regular expressions. BusyBox grep typically only supports basic regex without -E. Option B is less likely because locale affects character classes but not simple alternation.

Option C is false because GNU and BSD grep both support -E. Option D is false because -E enables extended regex on both implementations.

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

Options A, B, and D are correct: brace expansion, tilde expansion, and parameter expansion are all performed by bash. Alias expansion is not an expansion step; variable assignment is not an expansion.

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

Option A is correct because `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

Option A is correct: using 'for file in *' with quoting and [ -f ] handles spaces and ensures only regular files. Options B and C use command substitution which splits on whitespace. Option D treats all names as one string.

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