Domain 3Shell ScriptingCORE

Scripting

Creating simple shell scripts in Red Hat Enterprise Linux, using conditional logic, loops, positional arguments, user input processing, and error handling.

Domain: Domain 3: Create simple shell scripts•Updated: 2026-08-30
#Bash#Shell Scripting#Automation#CLI#Loops#Conditions

Scripting

This section covers shell scripting fundamentals in Red Hat Enterprise Linux, including script structure, conditional branching (if/case), iteration loops (for/while), positional arguments, user input handling, file test operators, and practical lab automation for RHCSA preparation.


Theory Questions

1. What is the correct shebang line for a Bash shell script?

The shebang line must be the first line of the script file, specifying the path to the interpreter binary.

  • Command(s): #!/bin/bash
  • Why: The shebang (#!) instructs the operating system kernel to execute the script using the Bash shell interpreter binary located at /bin/bash.
  • Gotchas: Omitting the exclamation mark (#!) converts the line into a standard shell comment, causing the OS to execute the script using the default system shell instead.
  • Verify: head -n 1 script.sh

2. What is the purpose of exit 0 at the end of a script?

exit 0 terminates script execution cleanly and returns a status code of zero to the parent process.

  • Command(s): exit 0
  • Why: In Linux, an exit code of 0 indicates success, whereas any non-zero exit status code (1 through 255) signifies an error or failure condition.
  • Gotchas: Omitting an explicit exit statement causes the script to return the exit code of the last executed command, which may lead to false positives in automated pipelines.
  • Verify: Execute the script and inspect the return code using echo $?.

3. How do you pause script execution to wait for user input?

Use the read command paired with a prompt message flag -p.

  • Command(s): read -r -p "Press Enter to continue..."
  • Why: read halts process execution until input is received from standard input (stdin). The -r flag prevents backslash character escaping.
  • Gotchas: Using sleep pauses execution for a fixed duration rather than waiting for interactive user intervention.
  • Verify: Run the script interactively and observe the input prompt pause.

4. How do you store the first command-line argument passed to a script in a variable?

Assign the first positional parameter ($1) to a user-defined variable.

  • Command(s): myvar="$1"
  • Why: Shell scripts map command-line arguments into numeric positional parameters ($1, $2, $3, etc.).
  • Gotchas: Omitting double quotes around "$1" causes variable assignment to fail or truncate if the passed argument contains spaces.
  • Verify: echo "$myvar"

5. How do positional parameters distinguish between different arguments passed into a script?

Arguments are indexed sequentially by integer position starting at 1.

  • Command(s): echo "Script: $0 | Arg1: $1 | Arg2: $2 | Arg3: $3"
  • Why: $0 holds the script name or path as invoked, while $1, $2, and $3 capture the first, second, and third command-line arguments respectively.
  • Gotchas: Do not confuse $1 (the first argument) with $0 (the script invocation path itself).
  • Verify: ./script.sh foo bar baz

6. How do you close an if conditional block in Bash?

Close an if statement block using the fi keyword.

  • Command(s): fi
  • Why: fi marks the explicit end of an if construct in Bash syntax.
  • Gotchas: Omitting fi causes Bash to raise a syntax error: unexpected end of file.
  • Verify: Validate script syntax without execution using bash -n script.sh.

7. How do you construct a complete if-elif-else conditional structure?

Chain conditional tests using if, elif, and else, terminated by fi.

  • Command(s):
    if [ "$1" == "a" ]; then
        echo "Option A selected"
    elif [ "$1" == "b" ]; then
        echo "Option B selected"
    else
        echo "Invalid selection"
    fi

* **Why:** Evaluates conditions sequentially. The first matching `then` block executes; if no conditions match, the `else` block executes.
* **Gotchas:** Missing spaces inside test brackets `[ ]` (e.g., `["$1"=="a"]`) produces syntax syntax errors.
* **Verify:** `bash -n script.sh`

---

### 8. How do you construct a standard `for` loop in Bash?

Use `for item in list; do ... done` block syntax.

* **Command(s):**
```bash
for i in {1..5}; do
    echo "Iteration $i"
done
  • Why: for iterates over a sequence or array; do marks the beginning of the execution block, and done closes the loop.
  • Gotchas: Omitting do or done generates syntax parsing errors.
  • Verify: bash -n script.sh

9. How do you send an email with a specific subject line from within a script?

Pipe message text into the mail or mailx utility using the -s subject option.

  • Command(s): echo "Message body text" | mail -s "Notification Subject" root
  • Why: -s specifies the email subject line string, and arguments specify target user accounts or email addresses.
  • Gotchas: Ensure local mail transfer agent (MTA) services (such as Postfix) are running on the system to route generated messages.
  • Verify: mail -u root

10. How do you add a catch-all default clause inside a case statement?

Use the asterisk wildcard pattern (*) as the final choice entry.

  • Command(s):
case "$1" in
    start) echo "Starting service" ;;
    stop)  echo "Stopping service" ;;
    *)     echo "Usage: $0 {start|stop}" ;;
esac
  • Why: The *) pattern matches any string that fails to match prior explicitly defined options in the case block.
  • Gotchas: Omitting double semicolons ;; at the end of the *) block causes syntax parsing failure.
  • Verify: bash -n script.sh

11. What happens if a script omits the shebang line?

The operating system executes the script using the active invocation shell or falls back to /bin/sh.

  • Command(s): N/A (Execution behavior)
  • Why: Without an explicit interpreter directive, the executing environment assumes standard shell compatibility mode.
  • Gotchas: Advanced Bash-specific features (such as double bracket tests [[ ]], arrays, or regex matching) may fail if executed under legacy /bin/sh.
  • Verify: Execute ./script.sh without a shebang and inspect error outputs.

12. How do you check whether a string variable is empty or unset?

Use the -z test operator inside bracket evaluation statements.

  • Command(s): [ -z "$var" ]
  • Why: The -z operator evaluates to true if the string length of the target variable is zero.
  • Gotchas: Omitting double quotes around "$var" causes a unary operator expected error if the variable is empty or unset.
  • Verify: var=""; [ -z "$var" ] && echo "Variable is empty"

13. How do you count the total number of command-line arguments passed to a script?

Reference the special internal parameter $#.

  • Command(s): echo "Total arguments: $#"
  • Why: $# evaluates to an integer representing the exact count of positional parameters supplied at script execution.
  • Gotchas: Do not confuse $# (argument count) with $* or $@ (which hold the argument values themselves).
  • Verify: ./script.sh arg1 arg2 arg3 (returns Total arguments: 3).

14. How do you reference all command-line arguments as separate quoted strings?

Use the special parameter array syntax "$@".

  • Command(s): for arg in "$@"; do echo "$arg"; done
  • Why: "$@" expands each positional argument to a separate word, preserving internal spaces within individual arguments.
  • Gotchas: Using "$*" concatenates all arguments into a single string joined by the first character of the IFS variable (usually space), breaking argument boundaries.
  • Verify: ./script.sh "first argument" "second argument"

15. How do you capture interactive keyboard input into a script variable?

Use read -r followed by the target variable identifier.

  • Command(s): read -r user_input
  • Why: Captures user keystrokes from standard input into user_input until the user presses Enter.
  • Gotchas: Always include -r to prevent read from interpreting backslash escape sequences unexpectedly.
  • Verify: read -r input && echo "Received: $input"

16. How do you test if a file exists and execute a command if it does NOT exist?

Combine the file existence test (! -e) with logical AND (&&) or an if structure.

  • Command(s): [ ! -e /path/to/file ] && touch /path/to/file
  • Why: -e tests for file existence, ! negates the result (true if missing), and && executes the secondary command only if the test succeeds.
  • Gotchas: Using -f instead of -e tests exclusively for regular files, ignoring existing directories or symbolic links with the same name.
  • Verify: Run the command twice; the second run will perform no action as the target file now exists.

17. How do you distinguish whether a file system path is a regular file or a directory?

Use the -f test operator for files and -d for directories.

  • Command(s):
if [ -f "$path" ]; then
    echo "$path is a regular file"
elif [ -d "$path" ]; then
    echo "$path is a directory"
fi
  • Why: -f evaluates true only for regular files, while -d evaluates true only for directory paths.
  • Gotchas: Using -e returns true for both files and directories without distinguishing between item types.
  • Verify: [ -f /etc/passwd ] && [ -d /etc ] && echo "Tests passed"

18. How do you evaluate a range of sequential numbers in a script loop?

Use sequence expansion {start..end} or the seq command.

  • Command(s): for i in {1..10}; do echo "$i"; done
  • Why: {1..10} expands into a space-separated list of integers from 1 to 10 before loop execution.
  • Gotchas: Variable expansion inside braces (e.g., {1..$max}) is not supported in Bash; use seq 1 "$max" for dynamic ranges instead.
  • Verify: for i in {1..5}; do echo "$i"; done

19. How is an elif statement closed in Bash?

An elif block does not have its own individual closing keyword; it is closed by subsequent elif statements, an else block, or the final fi.

  • Command(s): fi
  • Why: elif represents an intermediate branch of a parent if construct and shares the terminating fi statement.
  • Gotchas: Attempting to use non-existent keywords like endelif causes syntax parsing errors.
  • Verify: bash -n script.sh

20. How do you terminate a specific clause block inside a case statement?

End each matching pattern block using double semicolons ;;.

  • Command(s): ;;
  • Why: ;; acts as a break statement, preventing execution from falling through into subsequent pattern blocks.
  • Gotchas: Omitting ;; at the end of a case pattern clause causes script syntax errors.
  • Verify: bash -n script.sh

Lab Tasks

Script Writing Practice

Develop executable shell scripts handling command-line positional arguments, string evaluation, local mail sending, interactive timers, and arithmetic expressions.

Configuration Steps

# 1. Create Script 1: Argument Handler
cat << 'EOF' > /usr/local/bin/arg_handler.sh
#!/bin/bash
# Script 1 - Argument Handler

case "$1" in
    one)
        touch /tmp/one
        ;;
    two)
        echo "Message for option two" | mail -s "two" root
        ;;
    *)
        echo "Usage: $0 {one|two}"
        exit 1
        ;;
esac
exit 0
EOF

# Grant execute permissions to Script 1
chmod +x /usr/local/bin/arg_handler.sh


# 2. Create Script 2: Countdown Timer
cat << 'EOF' > /usr/local/bin/countdown.sh
#!/bin/bash
# Script 2 - Countdown Timer

if [ -z "$1" ] \vert{}\vert{} [ "$#" -ne 1 ]; then
    echo "Usage: $0 <minutes>"
    exit 1
fi

total_seconds=$(( $1 * 60 ))

while [ "$total_seconds" -gt 0 ]; do
    echo "there are $total_seconds seconds remaining"
    sleep 1
    total_seconds=$(( total_seconds - 1 ))
done

echo "time is over"
exit 0
EOF

# Grant execute permissions to Script 2
chmod +x /usr/local/bin/countdown.sh
  • Why:

  • chmod +x sets the execution bit on target script files so they can be run directly as commands.

  • case "$1" cleanly maps command-line string arguments to file creation or mail commands.

  • [ -z "$1" ] || [ "$#" -ne 1 ] validates that exactly one input argument is provided.

  • $(( $1 * 60 )) performs Bash integer arithmetic to convert input minutes into total seconds.

  • while [ "$total_seconds" -gt 0 ] iterates second-by-second using sleep 1 until the counter reaches zero.

  • Gotchas:

  • Forgetting to set execution permissions (chmod +x) produces a Permission denied error upon command invocation.

  • Omitting argument validation in countdown.sh leads to arithmetic errors if no parameter is supplied.

Verification Procedures

Validate syntax integrity and test script execution logic.

# Verify script syntax without executing logic
bash -n /usr/local/bin/arg_handler.sh
bash -n /usr/local/bin/countdown.sh

# Test Script 1: Execute with argument 'one' and verify file creation
/usr/local/bin/arg_handler.sh one
ls -l /tmp/one

# Test Script 1: Execute with argument 'two' and check root mail inbox
/usr/local/bin/arg_handler.sh two
mail -u root

# Test Script 2: Execute countdown with 0 minutes for instant zero-condition validation
/usr/local/bin/countdown.sh 0