Courseiva

CCNA Create simple shell scripts Questions

28 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

This is the exact purpose of `set -e`, also known as `errexit`. When enabled, the shell immediately exits if any simple command, pipeline, or compound command (outside of contexts like `if`, `while`, `until`, `!`, or `&&`/`||` left operands) returns a non-zero status. This halts the script at the first error rather than continuing with unchecked failures.

Why this answer

The 'set -e' option instructs the shell to exit immediately if any command or pipeline returns a non-zero exit status (i.e., fails). This is commonly used in scripts to prevent execution from continuing after an error, which could lead to unpredictable behavior or data corruption. It does not affect variable handling, command printing, or debug verbosity.

Exam trap

The trap here is that candidates often confuse 'set -e' with 'set -u' (unset variable errors) or with debugging options like 'set -x' or 'set -v', because all are shell options that begin with 'set -' but have very different effects.

How to eliminate wrong answers

Option A is wrong because treating unset variables as an error is the behavior of 'set -u', not 'set -e'. Option B is wrong because printing each command before execution is the effect of 'set -x' (or 'set -o xtrace'), not 'set -e'. Option C is wrong because enabling debug mode with verbose output is achieved by 'set -v' (or 'set -o verbose'), which prints shell input lines as they are read, not by 'set -e'.

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

A script run via cron or an administrator's shell inherits a minimal PATH and can fail silently if critical commands like df or awk are missing or are non-executable. Including error handling, such as verifying prerequisites with command -v and checking the exit status of df, prevents the script from issuing false alerts or exiting with unrelated error codes. A graceful exit that logs a clear diagnostic message to stderr or syslog makes the failure self-evident and allows administrators to correct the environment rather than debug mysterious output.

Why this answer

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

The `bash -n script.sh` command invokes Bash's noexec mode, which causes the shell to read and parse the entire script but not execute any of its commands. The parser reports any syntax errors with the offending line number and returns a non-zero exit status, making this the standard method for syntax-checking a Bash script. Note that this check only validates grammar, not logical or runtime errors.

Why this answer

The `bash -n` (noexec) option performs syntax checking on a script without executing any commands. If a syntax error exists, Bash reports the error along with the line number, making it the correct tool for identifying syntax errors in a script without running it.

Exam trap

The Red Hat RHCSA exam often tests the distinction between syntax checking (`-n`) and execution tracing (`-x` or `-v`), so candidates mistakenly choose `set -x` thinking it will catch errors without execution, but it actually runs the script and only shows debug output.

How to eliminate wrong answers

Option A is wrong because `which bash` only displays the path to the Bash executable, not perform any syntax checking. Option C is wrong because `set -x` enables execution tracing (debug mode) that prints commands as they execute, but it does not prevent execution and does not report syntax errors without running the script. Option D is wrong because `bash -v` prints script lines as they are read, but it still executes the script and will not stop at a syntax error to report the line number without execution.

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

This option uses `df /` without `-h`, which produces a stable, machine-parseable output. The `awk` command extracts the fifth field (the percentage used) and `tr` removes the percent sign. This is portable across different Unix/Linux systems.

Why this answer

It uses `df /` (without `-h`) to produce a stable, machine-parseable output where the fifth field (`$5`) is always the percentage used, and `awk` reliably extracts it. The `tr -d '%'` removes the percent sign for numeric comparison. This approach avoids the portability issues of parsing human-readable output from `df -h`, which can vary in column spacing and ordering across different Unix/Linux systems.

Exam trap

The trap on the RHCSA exam is that candidates assume `-h` is always better for readability, but the exam tests understanding that human-readable output is unreliable for scripting due to inconsistent column formatting across different Unix/Linux distributions.

How to eliminate wrong answers

Option A is wrong because `sed 's/.* //'` greedily removes everything up to the last space, which fails if the mount point contains spaces or if the output format varies (e.g., long device names). Option B is wrong because `cut -d' ' -f5` splits on single spaces, but `df -h` output often uses multiple spaces or tabs as delimiters, causing `cut` to misinterpret columns. Option D is wrong because `grep -oP` uses Perl-compatible regex, which is not available in all environments (e.g., older systems or minimal installations), and the pattern `\d+%` may match unexpected text like '1%' in a filesystem name.

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

The command uses $home, which is a different variable name from $HOME because bash is case-sensitive. Environment variables like HOME are uppercase by convention, and the lowercase $home is not defined in any standard shell session, so it expands to an empty string. Assigning or exporting a lowercase home would require the script author to have previously set it, and echo "$home" would then output that value rather than the actual home directory. The only correct fix is to change the script to use $HOME (or ${HOME}).

Why this answer

Bash variable names are case-sensitive, so $home is a distinct variable from the standard $HOME environment variable. Since 'home' was never assigned, it expands to an empty string, producing the observed output. The correct reference is $HOME.

Exam trap

EX200 often tests whether candidates overlook shell case-sensitivity and instead blame environment configuration or shell choice, when the real cause is a simple variable-name typo.

How to eliminate wrong answers

Option A is wrong because HOME is virtually always set in an interactive login environment; the issue is the variable name case, not its absence. Option C is wrong because both sh and bash treat variable names as case-sensitive, so running under sh would produce the same empty result. Option D is wrong because even root has a home directory (typically /root) and HOME is set for root; the script would still fail due to the lowercase variable name.

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

The shell and many programs follow the convention that exit status 0 means successful completion, while any non-zero value signals an error, warning, or unusual termination. This convention is pervasive across UNIX-like systems and is relied upon by scripts, continuous integration pipelines, and command-line tools to make control-flow decisions. While specific programs may assign different meanings to specific non-zero codes, the general rule remains that non-zero means the command did not complete as intended.

Why this answer

In shell scripting, exit codes are integers from 0 to 255. An exit code of 0 conventionally indicates success, while any non-zero value (1–255) indicates a failure or error condition. Option B is correct because a non-zero exit code usually signals that the command or script did not complete successfully.

Exam trap

A common pitfall is confusing the default exit code: many candidates assume the script always exits with 0 unless 'exit 1' is used, but actually the default exit code is the exit status of the last command run in the script.

7
MCQmedium

A sysadmin writes a shell script /usr/local/bin/check_service.sh that must accept exactly two positional arguments: a service name and a threshold. The script begins with: #!/bin/bash if [ $# -ne 2 ]; then echo "Usage: $0 <service> <threshold>" exit 1 fi An operator runs the script as: ./check_service.sh httpd What is the exit status of the script, and what output is produced?

A.The script exits with status 0 because the usage message is displayed successfully.
B.The script exits with status 1 and prints the usage line to standard output.
C.The script terminates with a syntax error because $# is not a valid variable.
D.The script continues past the check and prompts for the missing threshold value.
AnswerB

Because only one argument is supplied, $# equals 1, the test [ $# -ne 2 ] is true, the usage message is echoed to standard output, and exit 1 terminates the script with status 1. This matches the intended argument-validation pattern.

Why this answer

The script validates its argument count with $# and the numeric test -ne. With one positional argument supplied, the condition is true, so the usage message is written to standard output and exit 1 ends execution with a non-zero status. This is the conventional way to signal misuse from a shell script.

Exam trap

The trap here is assuming that printing a usage message means the script succeeded, when the explicit exit 1 overrides that and returns failure to the caller.

8
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

This is the correct behavior. When the command substitution `$(ls /etc/*.conf)` is left unquoted, the shell splits the result using the characters in `IFS` (space, tab, and newline by default). A file named, for example, `app config.conf` becomes two loop tokens, `app` and `config.conf`, causing the loop body to run extra times with incorrect arguments. These partial names are unlikely to exist, so the script produces errors and fails to handle the actual .conf files that have spaces.

Why this answer

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.

9
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

When you execute a script by name or with ./script, the kernel starts a new shell process (child) with its own copy of the parent's environment. The export builtin marks VARIABLE for inheritance by that child, but any assignments or exports made inside the script modify only the child's environment, which is discarded when the script exits. Therefore the exported variable never appears in the parent shell, even though it is available to programs launched within the script. This is the fundamental process isolation you are observing.

Why this answer

When a script is executed with './export_script.sh', it runs in a sub-shell (a child process). The 'export' command within the script makes the variable available to that sub-shell and its own child processes, but not to the parent shell that invoked the script. Therefore, after the script exits, the variable MY_VAR is not defined in the parent shell's environment, resulting in an empty output from 'echo $MY_VAR'.

Exam trap

The trap here is that candidates often confuse 'export' with making a variable globally available across all shells, not realizing that export only propagates to child processes, not to the parent shell that executed the script.

How to eliminate wrong answers

Option A is wrong because if the script lacked execute permissions, the './export_script.sh' command would fail with a 'Permission denied' error, not produce an empty output after the script runs. Option C is wrong because the placement of 'export' after the variable assignment (e.g., MY_VAR=value; export MY_VAR) is syntactically correct and does not affect the variable's export status; the issue is the sub-shell boundary, not the order of commands. Option D is wrong because variable names in bash are case-sensitive but can be any case; uppercase is a convention for environment variables but not a requirement for inheritance—lowercase variables can be exported and inherited just as well.

10
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

Quoting variable expansions such as "$var" or "${var}" prevents the shell from performing word splitting (splitting the value on characters in IFS, typically whitespace) and pathname expansion (globbing) on the resulting tokens. Without quotes, a variable containing spaces or glob characters like '*' can be broken into multiple arguments or expanded into filenames in unexpected ways. Consistent quoting ensures that the value of the variable is passed as a single argument, which is essential for correctly handling filenames, paths, or data with special characters.

Why this answer

Option A is correct because quoting variable expansions such as "$var" prevents unintended word splitting and glob expansion, which are common sources of bugs and failures in shell scripts. Option C is correct because 'set -u' causes the shell to treat references to unset variables as an error and exit, catching typos and missing environment variables early. Option D is correct because 'set -e' makes the script exit immediately when a command returns a non-zero status, preventing execution from continuing after a failure.

Option B is not a reliability practice: 'echo "Error"' without redirection writes to stdout rather than stderr, so error messages may be missed or mixed with normal output. Option E is not recommended: using 'cat' to feed a while loop spawns an extra process and is less efficient than redirecting the file directly into the loop, and it does not by itself improve reliability.

Exam trap

The RHCSA exam often tests the misconception that 'echo' is sufficient for error output without considering redirection to stderr, and that 'cat' in while loops is a safe pattern, when in fact it introduces performance and reliability issues.

11
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 /etc/passwd` writes the line count followed by a space and the filename (e.g., `37 /etc/passwd`) to stdout. Command substitution captures that entire string into `lines`, so `echo $((lines + 1))` attempts to perform arithmetic on a value that is not a valid integer literal. Because the filename is embedded in the variable, the shell cannot evaluate the expression. This is the fundamental problem: `lines` is not a pure number.

Why this answer

The command substitution `$(wc -l /etc/passwd)` outputs the line count followed by a space and the filename `/etc/passwd`. This entire string (e.g., `35 /etc/passwd`) is stored in the variable `lines`. When `$((lines+1))` attempts arithmetic expansion, it fails because the string is not a pure integer, causing the shell to treat it as 0 or produce an error, resulting in an unexpected output.

Exam trap

Red Hat often tests the candidate's understanding that `wc` includes the filename in its output when given a file argument, and that arithmetic expansion requires a pure numeric string, causing candidates to overlook the need to strip the filename or use input redirection.

How to eliminate wrong answers

Option B is wrong because `wc -l` already counts lines correctly; the `-c` option counts bytes, not lines, and would not fix the issue. Option C is wrong because the `echo` command syntax is valid; the problem lies in the arithmetic expansion, not the echo itself. Option D is wrong because `$((...))` can read variables from command substitution as long as the variable contains a valid integer; the issue is that `lines` contains extra non-numeric text (the filename), not that the variable type is incompatible.

12
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 is the only option that explicitly handles the signal that is actually interrupting the script. The trap directive installs a handler for SIGINT, so when Ctrl-C is sent, the shell runs "rm -f $tempfile; exit" instead of simply dying. Because the trap is installed at the top level before the long task begins, it remains in effect throughout the task, and the explicit exit prevents the shell from continuing after the cleanup runs. This guarantees the temporary file is removed even on user interruption.

Why this answer

The EXIT trap is only triggered on normal script termination (e.g., reaching the end or an explicit `exit`), not on signals like SIGINT. By adding a separate trap for INT that explicitly removes the temp file and calls `exit`, the cleanup runs even when the user presses Ctrl+C, ensuring the temporary file is deleted.

Exam trap

Red Hat often tests the misconception that the EXIT trap handles all termination scenarios, including signals, when in fact it only runs on normal exit paths, not on unhandled signals like SIGINT.

How to eliminate wrong answers

Option A is wrong because moving the trap inside a subshell would cause the trap to apply only to the subshell, not the main script, and the subshell would exit immediately after the long task, defeating the purpose of the trap. Option B is wrong because `trap ... 0` is exactly equivalent to `trap ... EXIT` in bash; both trigger only on normal exit, not on signals, so this change would not fix the issue.

Option C is wrong because `set -e` causes the script to exit on any command failure, but it does not affect signal handling or trap execution; it would not ensure cleanup on SIGINT.

13
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 is a shell builtin that reads a line from standard input and splits it into words using IFS, assigning them to the listed variable names; when no variable is supplied, it stores the entire line in REPLY. Because it runs in the current shell process rather than a child process, the assigned variables remain available afterward, which is exactly what an interactive prompt requires. Its exit status reflects whether a line was actually read, so it also works in while loops.

Why this answer

The `read` built-in command is specifically designed to capture user input from standard input (stdin) during script execution, storing it in one or more variables. This makes it the correct choice for interactive scripts that require runtime input from the user.

Exam trap

Red Hat often tests the distinction between output commands (echo, printf) and input commands, expecting candidates to know that `read` is the only built-in among the options that directly captures user input into a variable.

How to eliminate wrong answers

Option B (printf) is wrong because it is used for formatted output, not for reading input; it writes to stdout. Option C (cat) is wrong because it concatenates and displays file contents, and while it can read from stdin if no file is given, it is not a shell built-in for capturing user input into a variable. Option D (echo) is wrong because it outputs text to the terminal and has no capability to read or capture input.

14
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

Unquoted variable expansions are subject to word splitting and pathname expansion, so a filename like 'My File.txt' would be split into two arguments, and a value containing '*' could expand to multiple files. Quoting, as in "$file", preserves the variable's value as one literal argument, preventing these transformations. This is essential when handling user input, file paths, or any value with whitespace or glob characters.

Why this answer

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.

15
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

The parameter expansion `${1:-.}` explicitly targets the first positional parameter (`$1`) and applies the `:-` operator: if `$1` is unset or null, the expansion substitutes the literal `.` (the current directory). This precisely fulfills the requirement to accept a directory argument with a sensible default when no argument is supplied, because `$1` is the first argument passed to the script, and the default value is only used when that argument is missing or empty.

Why this answer

`${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.

16
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

Declaring variables with `local` inside a function constrains their scope to that function and its called subshells, preventing them from leaking into and clobbering global variables. This avoids hard-to-trace side effects, strengthens reusability and recursion, and is a core principle of writing clean, modular Bash functions.

Why this answer

The 'local' keyword restricts a variable's scope to the function where it is declared, preventing unintended side effects on global variables. This is a recommended practice in RHEL shell scripting to maintain modularity and avoid namespace pollution.

Exam trap

In Red Hat RHCSA exams, the trap is that candidates may think 'set -e' is always a best practice for error handling, but Red Hat expects you to recognize that it can cause premature exits in scripts where non-zero exit codes are expected and handled conditionally.

17
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

The semicolon is a command terminator that allows rc=$? to execute regardless of how risky_command exited. After risky_command finishes, $? holds its exact exit status, and the assignment immediately stores it before any other command or expansion can alter it. The subsequent echo $rc then prints the saved value, making this the correct pattern for capturing a failure status without terminating the script.

Why this answer

It runs the risky command, captures its exit status immediately after in the `$?` variable, and then echoes it for logging. The script continues regardless of the command's success or failure, which meets the requirement. The `$?` variable holds the exit status of the last executed foreground command, so assigning it to `rc` right after `./risky_command` ensures the correct value is stored.

Exam trap

In Red Hat Enterprise Linux shell scripting, a common mistake is to use `set -e` or conditional operators like `&&` when the goal is to capture the exit status regardless of success or failure. The correct approach is to assign `$?` unconditionally immediately after the command.

How to eliminate wrong answers

Option A is wrong because `set -e` causes the shell to exit immediately if any command fails, which contradicts the requirement that the script should continue after a failure. Option B is wrong because `rc=$? ./risky_command` sets `rc` in the environment of `./risky_command` (not the current shell) and `$?` is evaluated before the command runs, so `rc` gets the exit status of the previous command, not `./risky_command`. Option D is wrong because `&&` makes the assignment `rc=$?` conditional on `./risky_command` succeeding; if the command fails, `rc` is never assigned, and the exit status is lost.

18
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

The `while read host; do ... done < hosts` construct is the correct approach because it reads the file line by line. On each iteration, `read` assigns the entire line (minus trailing newline) to the variable `host`, so the content is not subjected to word splitting or pathname expansion. This makes it robust for hostnames that might contain unusual characters, though for exact preservation one should add `IFS=` and `-r` to `read`. Additionally, the redirection `< hosts` attaches the file to the loop's standard input, and the loop runs in the current shell, so any variable updates inside the loop remain available afterward.

Why this answer

The `while read host; do ... done < hosts` construct reads the file line by line, preserving each hostname exactly as it appears, including spaces or special characters. This is the safest and most idiomatic way to process a list of hostnames in a shell script, as it avoids word splitting and glob expansion issues that can occur with other methods.

Exam trap

The trap here is that candidates often choose `for host in $(cat hosts)` because it looks simpler, but they overlook how word splitting and glob expansion can break the script when hostnames contain spaces, tabs, or wildcard characters.

How to eliminate wrong answers

Option B is wrong because it uses a for loop with `seq` and `wc -l`, which is unnecessarily complex and fragile; it requires counting lines first and then indexing into the file, which is error-prone and not a standard pattern for reading lines. Option C is wrong because `for host in $(cat hosts)` subjects the file content to word splitting and glob expansion, so hostnames with spaces or wildcard characters would be incorrectly split or expanded. Option D is wrong because `until read host` is syntactically invalid; `until` tests a condition at the top of the loop, but `read` returns a non-zero exit status at end-of-file, making the loop never execute its body (or execute it incorrectly), and the redirection `< hosts` is misplaced.

19
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

The correct action is to grant execute permission explicitly. The chmod +x command adds the execute bit (x) to the file's mode for the user, group, and others, which is required for the kernel to allow execve to run the script directly. Without this bit, the shell returns 'Permission denied' even though the user can read and write the file. Since the devops user already owns the file and has read/write permissions, adding the execute bit is the minimal, sufficient fix to make the script runnable.

Why this answer

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

20
Drag & Dropmedium

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

Drag or tap steps into the slots.

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

Why this order

The correct sequence for configuring a logical volume snapshot is to first create the snapshot with lvcreate -s, mount it to access its contents, perform necessary operations (such as backups), unmount the snapshot, and finally remove it to clean up. Common mistakes include mounting or operating on the snapshot before it exists, or removing it prematurely.

21
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

trap - SIGINT resets SIGINT to its default disposition, undoing the earlier ignore. The hyphen tells the shell to restore default handling rather than run a command, which is exactly the re-enable behaviour the script needs after ignoring Ctrl+C.

Why this answer

`trap - SIGINT` resets the signal handler for SIGINT to its default behavior. The `trap '' SIGINT` command sets an empty action, which ignores the signal; using `trap - signal` removes that custom handler and restores the default action (typically terminating the process).

Exam trap

The RHCSA exam often tests the subtle distinction between `trap '' signal` (ignore) and `trap - signal` (restore default), where candidates mistakenly think `trap signal` or `trap : signal` resets the handler.

How to eliminate wrong answers

Option B is wrong because `trap : SIGINT` sets the action to the null command `:`, which is a no-op that still ignores the signal (similar to `trap '' SIGINT`), not restoring the default. Option C is wrong because `trap 2` is invalid syntax; signal numbers must be preceded by a dash or used with a signal name, and this would attempt to set a command '2' for the signal, causing an error or unintended behavior. Option D is wrong because `trap SIGINT` without a command or dash is ambiguous and typically results in an error or sets the trap to an empty string, depending on the shell, but does not restore the default handler.

22
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

In the given script, if an intended command is followed by a [[ ... ]] test, $? will reflect the exit status of the [[ ]] evaluation, not the earlier command. For example, if the script does [[ -f file ]] after running an application, $? becomes 1 when file does not exist, even if the application succeeded. Because $? is overwritten by each subsequent command, any intervening conditional destroys the original exit value.

Why this answer

The `[[ ]]` conditional construct is a shell keyword that itself produces an exit status. When `$?` is checked immediately after `[[ ]]`, it captures the exit status of the `[[ ]]` evaluation (which is 0 if the condition is true, 1 if false), not the exit status of the command that was run before the `[[ ]]`. Since the developer always sees 'Success' printed, the `[[ ]]` condition must be evaluating to true (exit status 0), causing `$?` to be 0 and the script to always take the success path, regardless of the actual previous command's result.

Exam trap

The trap here is that candidates mistakenly think `$?` always reflects the original command's exit status, not realizing that `[[ ]]` is itself a command that resets `$?` to its own exit status, causing the check to always succeed if the `[[ ]]` expression is syntactically valid.

How to eliminate wrong answers

Option A is wrong because `[[ ]]` does not always evaluate to true; it evaluates to true (exit status 0) or false (exit status 1) based on the expression inside it. Option B is wrong because `$?` is set after every command, including shell builtins like `[[ ]]`, `[ ]`, and `echo`; it is not limited to external commands. Option D is wrong because `$?` does not always return 0 in a conditional; it returns the exit status of the most recently executed command, which can be non-zero if that command failed.

23
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

Setting IFS= ensures read does not trim leading or trailing whitespace from each line, preserving the exact content of the input. The -r flag prevents backslashes from being interpreted as escape characters, so paths like C:\new remain literal. Quoting "$line" in the echo command prevents word splitting and glob expansion, and < file.txt correctly redirects the file to the loop's stdin line by line. This combination is the canonical robust way to process lines in Bash.

Why this answer

It uses `IFS=` to preserve leading/trailing whitespace and `-r` to prevent backslash interpretation, ensuring each line is read exactly as it appears in the file. The `< file.txt` redirect feeds the file line by line into the `while` loop, which is the standard and safe method for line-by-line processing in Bash.

Exam trap

Red Hat often tests the distinction between `while read` loops and `for` loops with command substitution, trapping candidates who forget that `for line in $(cat file)` splits on all whitespace and expands globs, not just newlines.

How to eliminate wrong answers

Option A is wrong because `<<<` is a here-string that passes the literal string 'file.txt' as input, not the file contents, and `IFS=$'\n'` only splits on newlines but does not preserve other whitespace within lines. Option C is wrong because omitting `IFS=` causes `read` to strip leading/trailing whitespace (default IFS includes space and tab), and omitting `-r` causes backslashes to be interpreted as escape characters, altering the line content. Option D is wrong because `$(cat file.txt)` subjects the file to word splitting and glob expansion, breaking lines on any whitespace (spaces, tabs) and expanding wildcards like `*`, so it does not read lines correctly.

24
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

In a non-interactive shell, an unmatched glob like /var/log/myapp/*.log is not expanded and is passed literally to cp. cp then attempts to copy a file named `*.log`, which does not exist, producing a 'No such file or directory' error and creating no backup. Unless the script checks the glob result or has error handling, this failure can be silent, especially if cron's stderr output is not inspected.

Why this answer

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.

25
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 is a special two-byte sequence (0x23 0x21) followed by an absolute path to an interpreter, such as #!/bin/bash. When the kernel tries to execute a script directly, it reads the first line, sees the shebang, and launches the specified interpreter with the script as its argument. If the interpreter path is invalid, the script fails with a "bad interpreter" error, so the shebang is essential for scripts executed as standalone commands. However, a script can omit the shebang if it is explicitly run as the argument to an interpreter, e.g., bash script.sh.

Why this answer

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.

26
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

The shell expands `*.txt` to the names of matching files in the current directory, which in the given directory listing are `a.txt` and `b.txt`. The `for i in` loop assigns each name in turn to `i`, and `wc -l "$i"` prints the line count for each file. Files in subdirectories such as `backup` are not matched because globbing is not recursive unless `**` is used.

Why this answer

The script uses `for i in *.txt`, which by default only matches .txt files in the current directory, not in subdirectories. Since 'a.txt' and 'b.txt' are in the current directory, the loop iterates over them and runs `wc -l` on each, outputting their line counts. The 'backup' subdirectory is not traversed because the glob pattern does not include paths with directories.

Exam trap

Red Hat often tests the candidate's understanding that shell glob patterns like `*.txt` do not recurse into subdirectories, leading many to incorrectly assume that all .txt files in the entire directory tree are processed.

How to eliminate wrong answers

Option A is wrong because the for loop can iterate over files with spaces if the glob pattern is unquoted and the files are properly handled (though the script does not quote $i, which could cause issues with spaces, but the question states no files have spaces, so no error occurs). Option B is wrong because the glob `*.txt` does not match files in the 'backup' subdirectory; it only matches .txt files in the current directory. Option D is wrong because the glob pattern does not recursively include files in subdirectories; only files directly in the current directory are matched.

27
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

This answer correctly re-establishes trust by fetching the remote server's current public host keys with ssh-keyscan and appending them to the management server's known_hosts file. After this update, scp will find the new host key for that server and pass verification, allowing the cron job to run normally. To preserve security, the administrator should verify the retrieved fingerprints out-of-band (for example, by comparing the server's SSH host key fingerprint from the console) before adding them, because blindly accepting keys could still allow man-in-the-middle attacks.

Why this answer

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 the RHCSA exam expects 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.

28
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

The variable $var is empty or unset, and because it is referenced without double quotes, the shell expands it to an empty string and then removes it entirely during word splitting. That causes [ $var = value ] to become [ = value ], which the test command sees as two arguments; it tries to treat '=' as a unary operator, producing the 'unary operator expected' error. Properly quoting as [ "$var" = value ] would keep the empty argument and yield a valid comparison, confirming the diagnosis.

Why this answer

The error 'unary operator expected' occurs in bash when the `[ ]` test command encounters an empty or unset variable on the left side of a comparison operator. Since `$var` is empty, the expression `[ $var = 'value' ]` expands to `[ = 'value' ]`, which is syntactically invalid because the `=` operator expects a left operand. Option D correctly identifies this as the root cause.

Exam trap

The trap here is that candidates often blame the comparison operator (`=` vs `==`) or think the string contains spaces, when the real issue is an unquoted variable that becomes empty after expansion, causing a missing operand for the `=` operator. In a Red Hat environment, this is a common bash scripting pitfall.

How to eliminate wrong answers

Option A is wrong because the `=` operator is the correct string comparison operator inside single brackets `[ ]` in bash; `==` is also accepted but not required, and using `=` does not cause this error. Option B is wrong because if the string 'value' contained spaces, the error would be about too many arguments, not 'unary operator expected', and the script uses single quotes which preserve spaces. Option C is wrong because the script runs and produces an error, meaning it is being executed (likely by bash); a missing shebang would cause the script to be interpreted by the default shell or fail to run at all, not produce this specific runtime error.

Ready to test yourself?

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