CCNA Create simple shell scripts Questions

37 questions · Create simple shell scripts · All types, answers revealed

1
MCQeasy

An administrator writes a script that uses the 'set -e' option at the top. What is the primary effect of this option?

A.It treats unset variables as an error
B.It prints each command before execution
C.It enables debug mode with verbose output
D.It exits the script immediately if a command fails
AnswerD

C is correct. 'set -e' makes the script exit on any non-zero exit status.

Why this answer

Option C is correct because 'set -e' causes the shell to exit immediately if any command exits with a non-zero status, which helps in catching errors early. Option A is wrong because 'set -e' does not affect variable expansion. Option B is wrong because it is for 'set -u'.

Option D is wrong because it is for 'set -x'.

2
Multi-Selecteasy

A system administrator writes a shell script to monitor disk usage and send an alert if any partition exceeds 80%. Which TWO of the following are best practices for implementing this script?

Select 2 answers
A.Use `cat /proc/partitions` to retrieve partition sizes.
B.Include error handling to check for missing commands and exit gracefully.
C.Send alerts only via syslog (logger command).
D.Use `df -h` and parse the output to check usage percentages.
E.Use `du -h /` and parse the output.
AnswersB, D

Correct: error handling improves script robustness.

Why this answer

Option B is correct because robust shell scripts should always include error handling to verify that required commands (e.g., `df`, `awk`, `grep`) are available before proceeding. This prevents the script from failing silently or producing misleading output, and allows it to exit gracefully with a meaningful error message, which is a key best practice for production scripts.

Exam trap

Red Hat often tests the distinction between `df` (filesystem-level usage) and `du` (directory-level usage), and candidates mistakenly choose `du` because they think it shows disk usage, but it does not report capacity or percentage used.

3
MCQhard

A script has a syntax error. Which command will help identify the line number of the error without executing the script?

A.which bash
B.bash -n script.sh
C.set -x
D.bash -v script.sh
AnswerB

bash -n checks syntax only and reports errors with line numbers.

Why this answer

Option B is correct because 'bash -n script.sh' performs syntax checking only. Option A ('set -x') enables execution trace. Option C ('bash -v') prints lines as read.

Option D shows the path of bash.

4
MCQmedium

An administrator writes a script to check disk usage and send an alert if usage exceeds 80%. The script uses 'df -h /' and parses the output. To maintain portability and avoid common pitfalls, which approach is recommended?

A.Use 'df -h / | tail -1 | sed 's/.* //' | tr -d '%'
B.Use 'df -h / | tail -1 | cut -d' ' -f5'
C.Use 'df / | awk 'NR==2 {print $5}' | tr -d '%'
D.Use 'df -h / | grep -oP '\d+%'
AnswerC

A is correct. It grabs the second line and fifth column, which is the percentage.

Why this answer

Option A is correct because using 'awk' with the percentage column is robust and handles different 'df' output formats. Option B is wrong because 'cut' might break if output format varies. Option C is wrong because using 'sed' with a fixed position is fragile.

Option D is wrong because using 'grep' to extract the percentage can be unreliable.

5
MCQeasy

A new intern created a script to display the current user's home directory: #!/bin/bash echo "Home directory: $home" The script outputs 'Home directory: ' with nothing after the colon. What is the most likely cause?

A.The HOME variable is not set in the environment.
B.There is a typo: it should be $HOME, not $home.
C.The script is run with 'sh' instead of 'bash'.
D.The root user has no home directory.
AnswerB

bash is case-sensitive; $home is a different variable, likely unset.

Why this answer

Option D is correct because the variable name should be uppercase HOME, not lower case home. bash is case-sensitive, so $home is not set. Option A is possible but less likely because HOME is usually set. Option B is false; sh also sets HOME.

Option C is false; root has /root.

6
Multi-Selecthard

Which TWO of the following are correct statements about exit codes in shell scripts?

Select 2 answers
A.An exit code of 1 means success
B.A non-zero exit code usually indicates a failure
C.An exit code of -1 indicates a system error
D.If no 'exit' is used, the script exits with code 0
E.Using 'exit 1' in a script sets the exit code to 1
AnswersB, E

B is correct.

Why this answer

Options B and D are correct. B: A non-zero exit code indicates failure, zero success. D: 'exit 1' explicitly sets the exit code.

Option A is wrong because 'exit -1' is invalid; exit codes are modulo 256. Option C is wrong because an exit code of 0 indicates success. Option E is wrong because 'exit 0' is not the default; the default is the exit code of the last command.

7
MCQhard

You are a system administrator for a medium-sized company running Red Hat Enterprise Linux 8 on all servers. The development team has created a shell script that is supposed to be run nightly via cron to synchronize configuration files from a master server to multiple web servers. The script is located at /opt/scripts/sync_configs.sh and is owned by root. It uses rsync over SSH with key-based authentication. The script works perfectly when run manually by root, but when it runs via cron, the synchronization fails with the error 'Host key verification failed.' The script does not explicitly specify any SSH options. The cron job is configured in /etc/crontab as: `0 2 * * * root /opt/scripts/sync_configs.sh`. The SSH keys are stored in /root/.ssh/id_rsa and the known_hosts file contains the correct host key for the master server. What is the most likely cause of the failure, and what is the best course of action to resolve it?

A.The PATH variable in cron does not include /usr/bin/rsync. Add a full path to rsync in the script or set PATH in the crontab.
B.The script does not have execute permission for the root user. Run `chmod +x /opt/scripts/sync_configs.sh`.
C.The known_hosts file in /root/.ssh/ contains an incorrect host key for the master server. Remove the entry and reconnect manually to update it.
D.The cron environment lacks the SSH agent or the key is not loaded. Modify the script to use `ssh -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no` or add a line to load the key via `ssh-add`.
AnswerD

Cron does not have access to the SSH agent; explicitly specifying the private key and disabling strict host key checking (or adding the host key to known_hosts via script) resolves the issue.

Why this answer

D is correct because cron runs in a minimal environment that does not automatically load the SSH agent or add keys to it. When the script runs manually as root, the SSH agent is typically running and the key is loaded, but cron does not have access to the agent's socket. The error 'Host key verification failed' is misleading; the actual issue is that SSH cannot authenticate because the private key is not available to the agent, not that the host key is unknown.

Adding `ssh -i /root/.ssh/id_rsa` explicitly specifies the key file, bypassing the need for an agent, or using `ssh-add` in the script loads the key into an agent for the cron session.

Exam trap

The trap here is that candidates see 'Host key verification failed' and immediately think the known_hosts file is wrong (option C), but the real issue is that cron lacks the SSH agent environment, causing the key to not be loaded, which leads to authentication failure that manifests as a host key error.

How to eliminate wrong answers

Option A is wrong because the error message is 'Host key verification failed,' not 'rsync: command not found,' so PATH is not the issue; rsync is being found and executed. Option B is wrong because the script is owned by root and runs as root via cron, and the question states it works manually, so execute permission is already set. Option C is wrong because the known_hosts file contains the correct host key and the script works manually, so the host key is not incorrect; the error is about authentication, not host key verification.

8
MCQmedium

A junior admin writes a script that uses functions. They notice that a variable set inside a function is not available after the function call. What is the likely cause and best practice?

A.The variable was declared with 'local', change to 'global' keyword
B.The script must be sourced (.) instead of executed to retain variables
C.The function was called inside a subshell, use 'export' to make it global
D.In bash, variables declared in a function are local by default, use 'declare -g' to make them global
AnswerD

B is correct.

Why this answer

Option B is correct. Without 'declare -g', variables inside functions are local by default in bash. The solution is to use 'declare -g' to make them global.

Option A is wrong because 'export' is not needed for parent script. Option C is wrong because 'local' makes it local, not global. Option D is wrong because subshells (with parentheses) do not affect variable scoping.

9
MCQmedium

A system administrator writes the script shown. The /etc directory contains .conf files with spaces in their names (e.g., "my config.conf"). What is the most accurate description of the script's behavior?

A.The script will correctly process all .conf files, including those with spaces.
B.The script will only process the first .conf file and then exit.
C.The script will not execute because of a syntax error.
D.The script will split filenames with spaces into multiple words, causing errors.
AnswerD

Correct: command substitution with ls and no quotes causes word splitting.

Why this answer

Option D is correct because the script uses a for loop with `for file in /etc/*.conf`, which relies on shell globbing. When the glob expands, filenames with spaces (e.g., "my config.conf") are treated as separate words due to word splitting, causing the loop to iterate over each word rather than each file. This results in errors when commands like `echo` or `cp` receive broken paths.

Exam trap

Red Hat often tests the misconception that globbing automatically handles spaces, when in fact unquoted expansions cause word splitting that breaks filenames with spaces.

How to eliminate wrong answers

Option A is wrong because the script does not handle filenames with spaces; word splitting breaks them into multiple arguments. Option B is wrong because the loop does not exit after the first file; it continues iterating over all expanded words, but each iteration may fail due to incorrect filenames. Option C is wrong because there is no syntax error in the script; the for loop syntax is valid, and the issue is a runtime behavior problem with word splitting.

10
Multi-Selecteasy

Which TWO of the following are valid ways to make a shell script executable?

Select 2 answers
A.bash script.sh
B.chmod 755 script.sh
C.. script.sh
D.chmod u+x script.sh
E.chmod +x script.sh
AnswersB, E

B is correct: sets rwxr-xr-x.

Why this answer

Option A and B are correct. 'chmod +x script.sh' adds execute permission, and 'chmod 755 script.sh' sets rwxr-xr-x. Option C is wrong because '. script.sh' sources the script but does not set execute permission. Option D is wrong because 'chmod u+x' is a subset of +x but still valid; however, the question asks for two, and A and B are the most common.

Option E is wrong because 'bash script.sh' runs without execute bit.

11
MCQmedium

A system administrator needs to create a shell script that checks if the user 'jdoe' exists in the system and, if not, creates the user with a home directory. The script should also verify that the creation was successful. Which of the following script snippets correctly implements this logic?

A.if grep -q '^jdoe:' /etc/passwd; then echo 'Exists'; else useradd 'jdoe' && echo 'Created'; fi
B.if id 'jdoe' &>/dev/null; then echo 'Exists'; else useradd -m 'jdoe' && echo 'Created' || echo 'Failed'; fi
C.if ! id 'jdoe' &>/dev/null; then useradd -m 'jdoe'; else echo 'Exists'; fi
D.[ -z $(id 'jdoe' 2>/dev/null) ] && useradd -m 'jdoe' && echo 'Created'
AnswerB

Correctly checks existence, creates with home dir, and verifies.

Why this answer

Option B is correct because it uses `id` to check for the user's existence (redirecting output to /dev/null to suppress messages), then uses `useradd -m` to create the user with a home directory. The `&&` and `||` operators ensure that success or failure of the creation is explicitly reported, fulfilling the requirement to verify successful creation.

Exam trap

Red Hat often tests the misconception that grepping /etc/passwd is sufficient for user existence checks, but the trap here is that modern systems may use remote authentication sources, so `id` is the correct command to query all NSS sources.

How to eliminate wrong answers

Option A is wrong because it greps /etc/passwd for '^jdoe:', which can produce false negatives if the user exists in LDAP or other NSS sources, and it does not create a home directory (missing -m). Option C is wrong because it does not verify that the creation was successful; it only runs useradd without checking its exit status. Option D is wrong because the `[ -z ... ]` test is unreliable (the command substitution may produce unexpected output or errors), and it does not handle the case where the user already exists (it would attempt to create the user again, which would fail).

12
MCQhard

A script uses 'read' to get user input and then performs an action based on the input. However, when the script is piped (e.g., './script.sh | othercommand'), the read command does not wait for input and the script continues with empty variable. How can this be fixed?

A.Use 'stdbuf -i0' before the script invocation to set stdin unbuffered
B.Use 'exec < /dev/tty' at the start of the script
C.Use 'read input < /dev/tty' instead of just 'read input'
D.Use 'read -t 0 input' to force immediate read
AnswerC

B is correct. This reads directly from the terminal.

Why this answer

Option B is correct because redirecting 'read' from /dev/tty forces it to read from the terminal even if stdin is a pipe. Option A is wrong because 'stdbuf' might not help with 'read'. Option C is wrong because 'read -t' sets a timeout, not a cure.

Option D is wrong because changing stdin for the whole script would break piping.

13
MCQhard

A user executes the script shown in the exhibit with './export_script.sh' and then runs 'echo $MY_VAR' in the same terminal. The output is empty. Why does this happen?

A.The script lacks execute permissions
B.The script runs in a sub-shell, so exported variables are not available to the parent shell
C.The 'export' command is incorrectly placed after the variable assignment
D.The variable name should be in uppercase for it to be inherited
AnswerB

B is correct.

Why this answer

Option B is correct because exporting a variable in a sub-process (the script) does not affect the parent shell's environment. Option A is wrong because 'export' is used correctly syntactically. Option C is wrong because the script is executable and runs.

Option D is wrong because the variable is set and exported in the script's environment.

14
Multi-Selectmedium

Which TWO methods correctly create a variable containing the number of regular files in the current directory (excluding . and ..)?

Select 2 answers
A.count=$(ls -1A | wc -l)
B.count=$(find . -maxdepth 1 -type f -printf '.' | wc -c)
C.count=$(stat -c%F * | grep -c 'regular file')
D.count=$(ls -1 | wc -l)
E.count=$(find . -maxdepth 1 -type f | wc -l)
AnswersB, E

Prints a dot per file; wc -c counts dots, immune to spaces/newlines in filenames.

Why this answer

Option B uses find with -type f to count files, correctly handling filenames with spaces. Option D uses find with -printf to print a character per file, then wc -c counts characters. Option A includes directories.

Option C uses ls -1A which shows all entries including directories. Option E uses stat but misses hidden files due to glob * not including dot files.

15
Multi-Selectmedium

Which THREE of the following are common practices to improve the reliability of shell scripts?

Select 3 answers
A.Always quote variable expansions unless word splitting is intended
B.Use 'echo "Error"' for error messages without redirection
C.Include 'set -u' to abort on unset variables
D.Include 'set -e' at the top of the script to exit on error
E.Use 'cat' to read files line by line in while loops
AnswersA, C, D

C is correct.

Why this answer

Options A, B, and C are correct. A: Using 'set -e' exits on error. B: Using 'set -u' treats unset variables as errors.

C: Quoting variables prevents word splitting. Option D is wrong because using 'cat' inside loops is inefficient; use I/O redirection. Option E is wrong because using 'echo' for errors is not ideal; use '>&2' to redirect to stderr.

16
MCQeasy

A script contains: lines=$(wc -l /etc/passwd); echo $((lines+1)). The output is unexpected. What is the problem?

A.lines contains a string including the filename, not just a number.
B.wc -l requires the -c option to count correctly.
C.The script has a syntax error in the echo command.
D.$((...)) cannot read a variable from command substitution.
AnswerA

wc -l outputs 'number filename', so lines is not a pure integer.

Why this answer

Option A is correct because wc -l output includes the filename, making $lines a string such as '45 /etc/passwd', which cannot be used in arithmetic. Option B is incorrect because -c counts characters. Option C is misleading; $((...)) works on integers.

Option D is wrong because the syntax is valid.

17
MCQhard

You maintain a script that performs a long-running task and must clean up temporary files if the script is interrupted. The script uses: #!/bin/bash tempfile=$(mktemp) trap "rm -f $tempfile" EXIT # long task sleep 100 You notice that if the script receives SIGINT (Ctrl+C), the temporary file is not removed. Investigation shows that the trap on EXIT is not executed on SIGINT. Which modification should be made?

A.Move the trap inside a subshell: (trap ... EXIT; long task).
B.Change `trap ... EXIT` to `trap ... 0`.
C.Add `set -e` at the beginning of the script.
D.Add a trap for INT: `trap "rm -f $tempfile; exit" INT`.
AnswerD

This catches SIGINT and performs cleanup then exits.

Why this answer

Option B is correct because adding a separate trap for INT ensures cleanup on Ctrl+C. Option A (adding 'set -e') does not help. Option C using 'EXIT' with 0 is same as EXIT; not triggered on SIGINT.

Option D putting the trap in a subshell would only affect the subshell.

18
MCQmedium

Which shell built-in can be used to read user input during script execution?

A.read
B.printf
C.cat
D.echo
AnswerA

read reads a line of input and assigns it to a variable.

Why this answer

Option B is correct because the 'read' built-in reads a line from standard input into a variable. Option A (echo) outputs, not reads. Option C (printf) formats output.

Option D (cat) reads files, not user input.

19
Multi-Selecthard

Which THREE of the following practices are recommended when creating simple shell scripts in a Red Hat Enterprise Linux environment to ensure reliability, security, and maintainability?

Select 3 answers
A.Use #!/bin/sh for compatibility, even if bash-specific features are needed.
B.Quote variables when used in commands, e.g., "$file" instead of $file.
C.Start the script with a shebang line, e.g., #!/bin/bash.
D.Include set -e at the beginning of the script to exit on any error.
E.Always run scripts by invoking the interpreter directly (e.g., bash script.sh) instead of making them executable.
AnswersB, C, D

Prevents unintended word splitting and pathname expansion.

Why this answer

Option B is correct because quoting variables (e.g., "$file") prevents word splitting and glob expansion, which can cause commands to operate on unexpected arguments or filenames with spaces. This is a fundamental shell scripting best practice that directly improves reliability and security by preserving the intended value of the variable.

Exam trap

The trap here is that candidates may think using #!/bin/sh is always safer for compatibility, but they overlook that it can break scripts relying on bash-specific features, and they may also believe invoking the interpreter directly is always acceptable, ignoring the portability and clarity benefits of an executable script with a shebang.

20
MCQeasy

A developer wants to create a script that accepts a directory path as an argument and creates a timestamped backup of that directory. If no argument is provided, it should back up the current directory. How should the script handle the argument?

A.dir=${1:-.}
B.dir=${@:-.}
C.dir=${0:-.}
D.dir=${?:-.}
AnswerA

D is correct. ${1:-.} uses $1 if set, otherwise '.'.

Why this answer

Option A is correct because `${1:-.}` uses the default value substitution syntax in bash: if parameter `$1` (the first positional argument) is unset or null, it expands to `.` (the current directory). This ensures the script backs up the supplied directory path or defaults to the current directory when no argument is provided, exactly matching the requirement.

Exam trap

Red Hat often tests the distinction between positional parameters (`$1`, `$2`, etc.) and special variables (`$@`, `$0`, `$?`), and the trap here is that candidates confuse `$1` with `$0` (the script name) or incorrectly assume `$@` works as a single default value, leading to option B or C.

How to eliminate wrong answers

Option B is wrong because `${@:-.}` expands to all positional arguments (`$@`) or `.` if none are provided, but `$@` is a list, not a single directory path, and using it in a backup command would break the script. Option C is wrong because `${0:-.}` refers to the script's own name (the zeroth argument), not the first argument passed by the user, so it would always expand to the script name instead of the intended directory. Option D is wrong because `${?:-.}` is not valid bash syntax; `$?` holds the exit status of the last command, and the `:-` substitution does not apply meaningfully here, causing a syntax error or unintended behavior.

21
Multi-Selecthard

Which THREE of the following are valid and recommended practices when writing shell scripts for RHEL?

Select 3 answers
A.Using 'local' keyword for variable declarations inside functions.
B.Always quoting variable expansions with double quotes.
C.Using [[ $var =~ regex ]] for pattern matching.
D.Using 'set -e' to exit on non-zero exit codes.
E.Using the 'source' command instead of '.' for readability.
AnswersA, B, C

Local variables prevent global namespace pollution.

Why this answer

Option A (using [[ with =~ for regex) is a bash-specific feature, but in RHEL bash is default, so it's valid and often recommended for readability. Option C (quoting variables) is a fundamental best practice to prevent word splitting. Option E (using local in functions) limits variable scope and avoids side effects.

Option B (source vs .) is a matter of preference; both work. Option D (set -e) can cause unexpected exits and is not always recommended.

22
MCQmedium

A script needs to execute a command that might fail, but the script should continue. The administrator wants to capture the exit status for logging. Which code snippet correctly implements this?

A.set -e; ./risky_command; rc=$?; echo $rc
B.rc=$? ./risky_command; echo $rc
C../risky_command; rc=$?; echo $rc
D../risky_command && rc=$?; echo $rc
AnswerC

C is correct. The exit status is always captured after command.

Why this answer

Option C is correct because the exit status is captured immediately after the command. Option A is wrong because using 'set -e' would exit on failure. Option B is wrong because chaining with '&&' would skip the status capture if the command fails.

Option D is wrong because the variable assignment and command execution are reversed.

23
MCQeasy

A system administrator needs to create a shell script that processes a list of hostnames stored in a file, one per line, and runs a command on each host. Which loop construct is most appropriate?

A.while read host; do ... done < hosts
B.for i in $(seq 1 $(wc -l < hosts)); do ... done
C.for host in $(cat hosts); do ... done
D.until read host; do ... done < hosts
AnswerA

B is correct. It reads each line correctly, even with spaces.

Why this answer

Option B is correct because the 'while read' loop is the standard way to read a file line by line in shell scripts, handling each line as a separate variable. Option A is wrong because 'for' with '$(cat file)' can break on spaces. Option C is wrong because it uses 'seq' unnecessarily.

Option D is wrong because 'until' is not suitable for this purpose.

24
MCQhard

You are a system administrator for a small company. The development team has created a shell script named 'deploy.sh' that automates deployment of a web application. The script is located at /home/devops/deploy.sh. The team reports that when they run the script with './deploy.sh' from the /home/devops directory, it fails with a 'Permission denied' error. However, running 'bash deploy.sh' works fine. Additionally, the script's first line is '#!/bin/bash' and the file permissions are '-rw-rw-r--'. The team wants to be able to run the script directly without typing 'bash'. Which of the following actions should you take to resolve the issue?

A.Change the shebang line to '#!/bin/sh' because bash is not the default shell.
B.Move the script to /usr/local/bin so it can be found in the PATH.
C.Add the execute permission to the script using 'chmod +x /home/devops/deploy.sh'.
D.Change the owner of the script to root using 'chown root:root /home/devops/deploy.sh'.
AnswerC

This makes the script directly executable.

Why this answer

Option C is correct because the 'Permission denied' error when running './deploy.sh' indicates that the script lacks execute permission. The current permissions '-rw-rw-r--' show read/write for owner and group, and read-only for others, but no execute bit. Adding execute permission with 'chmod +x' allows the script to be run directly via its shebang line.

Exam trap

Red Hat often tests the distinction between execute permission and interpreter availability; candidates may mistakenly think the shebang or PATH is the issue when the real problem is the missing execute bit.

How to eliminate wrong answers

Option A is wrong because the shebang '#!/bin/bash' is correct; bash is the default shell on Red Hat Enterprise Linux, and changing to '#!/bin/sh' would not resolve the missing execute permission. Option B is wrong because moving the script to /usr/local/bin does not grant execute permission; the script would still fail with 'Permission denied' when run directly. Option D is wrong because changing ownership to root does not add execute permission; the script would still lack the execute bit and fail with 'Permission denied'.

25
Drag & Dropmedium

Arrange the steps to configure a logical volume snapshot named 'snap_lv_data' of logical volume 'lv_data'.

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

Steps
Order

Why this order

Snapshots are created with -s flag, mounted, and removed after use.

26
MCQhard

A complex script uses 'trap' to handle signals. The admin writes 'trap '' SIGINT' to ignore Ctrl+C, but later in the script they want to re-enable the default behavior. Which command restores the default behavior for SIGINT?

A.trap - SIGINT
B.trap : SIGINT
C.trap 2
D.trap SIGINT
AnswerA

D is correct. The dash removes the trap.

Why this answer

Option D is correct because 'trap - SIGINT' removes the trap and restores default behavior. Option A is wrong because 'trap : SIGINT' sets a no-op trap, not default. Option B is wrong because 'trap 2' is not valid.

Option C is wrong because 'trap SIGINT' without '-' sets a trap to execute the signal name as a command, which is incorrect.

27
MCQmedium

A developer runs the script shown in the exhibit and always sees 'Success' printed, even when the previous command fails. What is the most likely cause?

A.The [[ ]] syntax always evaluates to true
B.The $? variable is only set after external commands, not builtins
C.The $? variable captures the exit status of the [[ command, not the intended command
D.The $? variable always returns 0 in a conditional
AnswerC

A is correct.

Why this answer

Option A is correct because $? is the exit status of the last command, which is the [[ command itself, not the command before the script. The [[ command returns 0 because the comparison is syntactically correct. Option B is wrong because $? is not the script's PID.

Option C is wrong because [[ ]] does not return the negation. Option D is wrong because $? is set correctly but for the wrong command.

28
MCQmedium

You are tasked with creating a script that reads a list of usernames from /tmp/users.txt, one per line, and creates a home directory for each user using `mkdir /home/$username`. The script is: #!/bin/bash while read username; do mkdir /home/$username done < /tmp/users.txt However, the script fails for usernames that contain spaces (e.g., 'john smith'). The error is 'mkdir: cannot create directory '/home/john': File exists' and then a separate directory for 'smith'. What is the best fix?

A.Change the loop to `for username in $(cat /tmp/users.txt)`.
B.Quote $username in the mkdir command as in `mkdir "/home/$username"`.
C.Add `set -f` to disable pathname expansion.
D.Use `while IFS= read -r username` to preserve the line as is.
AnswerD

IFS= and -r prevent field splitting and backslash processing.

Why this answer

Option B is correct because setting IFS= and using -r prevents the read command from splitting on spaces and disables backslash escapes. Option A quoting $username is necessary but not sufficient because read still splits. Option C would also split on spaces.

Option D disables globbing but does not fix word splitting.

29
MCQeasy

A script needs to read every line from a file and execute a command on each line. Which code block is correct and handles whitespace correctly?

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

IFS= preserves leading/trailing whitespace; -r prevents backslash escapes; quoting prevents word splitting.

Why this answer

Option C is correct because using IFS= and -r preserves whitespace and backslashes. Option A does not use -r, breaking backslashes. Option B splits on spaces and globs.

Option D uses an invalid here-string redirection for a file.

30
MCQeasy

A developer wrote a shell script that is intended to back up log files by copying all .log files from /var/log/myapp to /backup/logs. The script runs daily via cron but the backup folder is empty. The script contains the following line: `cp /var/log/myapp/*.log /backup/logs/`. What is the most likely reason the backup fails?

A.The PATH variable in cron is not set, so cp cannot be found.
B.The script does not have execute permission for the user running cron.
C.No .log files exist in /var/log/myapp at the time of script execution, causing the glob to match nothing.
D.The cron job is not enabled because the crontab syntax is incorrect.
AnswerC

If no files match, cp receives the literal '*' and fails silently if no error handling.

Why this answer

Option C is correct because the glob pattern `*.log` in the `cp` command is expanded by the shell at the time the script runs. If no `.log` files exist in `/var/log/myapp` when the cron job executes, the shell passes the literal string `*.log` to `cp`, which then fails with a 'No such file or directory' error (or, depending on shell settings, may silently do nothing). This is a common issue when log rotation or cleanup removes files before the backup runs.

Exam trap

Red Hat often tests the misconception that cron PATH or permissions are the root cause, but the real trap is that glob expansion happens at script execution time and an empty glob silently fails, leading to an empty backup destination.

How to eliminate wrong answers

Option A is wrong because `cp` is a built-in shell command or located in standard paths like `/bin/cp` or `/usr/bin/cp`, and cron typically sets a minimal PATH that includes `/usr/bin` and `/bin`, so `cp` is almost always found. Option B is wrong because the script itself does not need execute permission if it is invoked via `sh script.sh` or if the cron job line directly calls `sh`; the issue is about file existence, not permissions. Option D is wrong because the question states the script runs daily via cron, implying the crontab syntax is correct and the job is enabled; the backup folder is empty, not that the job fails to run.

31
Multi-Selecteasy

Which TWO of the following are true about creating simple shell scripts in Red Hat Enterprise Linux?

Select 2 answers
A.The shebang line (e.g., #!/bin/bash) is used to specify the interpreter.
B.Scripts must be stored in /usr/local/bin to be found by the shell.
C.The script file must have execute permission (chmod +x) to be run directly.
D.A script must be compiled before it can be run.
E.A script must have a .sh file extension to be executable.
AnswersA, C

The shebang line tells the system which interpreter to use.

Why this answer

Option A is correct because the shebang line (e.g., #!/bin/bash) tells the kernel which interpreter to use when executing the script. Without it, the shell may fall back to the default interpreter (often /bin/sh) or fail to run the script correctly. This is a fundamental requirement for any interpreted script in Linux.

Exam trap

Red Hat often tests the misconception that file extensions or specific directories are mandatory for script execution, when in fact the shebang line and execute permission are the only requirements.

32
Matchingmedium

Match each package management command to its action.

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

Concepts
Matches

Install a package with dependencies

Uninstall a package

Update all packages to latest versions

Show all installed packages

Why these pairings

DNF is the default package manager in RHEL 8/9.

33
MCQhard

A sysadmin creates a script to rotate log files. The script uses 'find /var/log -type f -name "*.log" -mtime +30 -exec gzip {} \;' but some log files are not compressed. The script runs as root. What is the most likely reason some files remain uncompressed?

A.The log files are already compressed (.gz extension), and gzip fails silently
B.Another process deletes log files between find's detection and execution, causing 'find' to error on missing files
C.The script lacks proper quoting around {} which causes gzip to fail on files with spaces
D.The '-mtime +30' flag selects files newer than 30 days, so old files are excluded
AnswerB

A is correct. The 'find -exec' can fail if files are removed concurrently.

Why this answer

Option A is correct because the 'find' command with '-exec' will fail if any file in the list is deleted (rotated) during execution, causing the whole command to produce errors and skip subsequent files. Option B is wrong because compression failure is less likely. Option C is wrong because '-mtime +30' means older than 30 days, not newer.

Option D is wrong because 'gzip' handles spaces with proper quoting.

34
MCQmedium

Refer to the exhibit. A junior admin runs this script as root, but it always prints 'httpd is running' even when httpd is stopped. What is the most likely cause?

A.The script is not executable and is run with `sh script.sh`, causing the shebang to be ignored.
B.The variable SERVICE is misspelled as "HTTPD" in the condition.
C.The `systemctl` command requires root privileges, and the script is run as a non-root user.
D.The script uses the test command `[` instead of directly using the command as the condition, causing the condition to always be true.
AnswerD

`[ systemctl ... ]` always evaluates to true because it tests the string.

Why this answer

Option D is correct because when a command is used as a condition inside `[ ]`, the `test` builtin evaluates the exit status of the command inside the brackets, not the command itself. In this script, `[ systemctl is-active httpd ]` always returns true (exit code 0) because `[` treats the string "systemctl" as a non-empty string, which is always true. The correct syntax is to use the command directly as the condition: `if systemctl is-active httpd; then`.

Exam trap

The trap here is that candidates mistakenly think the `[ ]` syntax is required for all conditions, not realizing that `[` is actually a command that evaluates its arguments as a test expression, not as a command to execute.

How to eliminate wrong answers

Option A is wrong because running a script with `sh script.sh` explicitly invokes the shell interpreter, so the shebang is irrelevant; the script will still execute correctly regardless of the shebang. Option B is wrong because the variable name `SERVICE` is not misspelled as "HTTPD" in the condition; the condition uses `systemctl is-active httpd` directly, not a variable. Option C is wrong because the script is run as root (as stated in the question), so root privileges are not an issue; the problem persists even with root.

35
MCQeasy

Consider the script in the exhibit. The script is run in a directory containing 'a.txt' and 'b.txt' but also has a subdirectory 'backup' with .txt files. What will be the output?

A.An error because the for loop cannot iterate over files with spaces
B.Line counts for .txt files in 'backup' only
C.Line counts for 'a.txt' and 'b.txt' only
D.Line counts for all .txt files including those in 'backup'
AnswerC

C is correct.

Why this answer

Option C is correct because the wildcard '*.txt' only matches files in the current directory, not subdirectories. It will count lines in 'a.txt' and 'b.txt' only. Option A is wrong because it does not include backup files.

Option B is wrong because it would count subdirectory files only if the glob expanded to them, which it does not. Option D is wrong because the script will run without error.

36
MCQhard

An organization uses a shell script that runs daily via cron on a central management server to archive logs from 50 remote Red Hat Enterprise Linux servers. The script uses `scp` with SSH key-based authentication (passwordless) to transfer files. Recently, after a security team rotated the SSH host keys on all remote servers, the script started failing with 'Host key verification failed' errors. The administrator needs to restore automated log transfers without compromising security. The remote servers are in a controlled internal network, and the management server's `~/.ssh/known_hosts` file is not centrally managed. Which course of action should the administrator take?

A.Add the -o StrictHostKeyChecking=no option to the scp command in the script.
B.Use ssh-keyscan to retrieve the new host keys and add them to the management server's known_hosts file.
C.Modify the sshd_config on each remote server to disable host key checking.
D.Replace scp with rsync in the script, as rsync uses a different authentication method.
AnswerB

Correct: updates known_hosts with new keys, re-establishing trust securely.

Why this answer

Option B is correct because using `ssh-keyscan` to retrieve the new host keys and add them to the management server's `known_hosts` file is the proper method to update host keys without disabling security. This approach maintains SSH host key verification, which prevents man-in-the-middle attacks, while allowing the script to authenticate the remote servers after the key rotation.

Exam trap

The trap here is that candidates may think disabling host key checking (Option A) is an acceptable quick fix, but Cisco tests the understanding that `StrictHostKeyChecking=no` is a security risk and that the correct approach is to update the `known_hosts` file with the new keys using `ssh-keyscan`.

How to eliminate wrong answers

Option A is wrong because adding `-o StrictHostKeyChecking=no` disables host key verification entirely, which compromises security by making the system vulnerable to man-in-the-middle attacks; it is a dangerous workaround, not a fix. Option C is wrong because modifying `sshd_config` on remote servers to disable host key checking is a server-side change that does not address the client-side `known_hosts` mismatch and also weakens SSH security globally. Option D is wrong because `rsync` uses the same SSH transport and authentication mechanism as `scp`, so it would still fail with the same 'Host key verification failed' error; it does not use a different authentication method.

37
MCQhard

Refer to the exhibit. The script produces the error shown. What is the most likely cause?

A.The = operator should be == for string comparison.
B.The string 'value' contains spaces.
C.The script is missing a valid shebang.
D.The variable $var is empty or unset.
AnswerD

An empty variable leads to a missing operand error in [ ].

Why this answer

Option A is correct: if $var is empty or unset, the test becomes [ = value ], which is a unary operator error. Option B is incorrect because the string 'value' has no spaces. Option C is incorrect because = is valid for string comparison inside single brackets.

Option D is incorrect because the shebang is present.

Ready to test yourself?

Try a timed practice session using only Create simple shell scripts questions.