Skip to content
Menu

RHSA: Shell Scripting

Shell Scripting Overview

  • Definition: Writing a series of shell commands in a file (script) to automate tasks.
  • Purpose: Execute multiple commands together without manual repetition.
  • File Extension: Typically ends with .sh.

Why Shell Scripting is Important

  • Automation: Saves time and reduces errors.
  • Consistency: Same result every time across multiple systems.
  • Efficiency: Handles tasks that would take hours manually.

What is a Shell?

  • Role: Interface between user and OS kernel.
  • Common Shells: Bash (most common on RHEL), SH, ZSH, KSH.
  • Bash: Preferred for beginners and scripting.

Uses of Shell Scripts

  • Automating backups.
  • Monitoring system logs.
  • Starting/stopping services.
  • Creating users.
  • Scheduling tasks (cron jobs).
  • Cleaning temporary files.
  • Software installation/configuration.

Basic Script Structure

  • Shebang: #!/bin/bash → Specifies interpreter.
  • Commands: Regular shell commands (e.g., echo, date, ls).
  • Execution: ./myscript.sh.

Power Features

  • Logic: if-else conditions for decision-making.
  • Loops: Repeat tasks efficiently.
  • Variables: Store and reuse values.
  • Example: Internet connectivity check using ping and conditional statements.

Benefits for RHCSA & Sysadmins

  • Essential for automation in real-world tasks.
  • Common scripts: disk usage checks, log rotation, service management, network configuration.
  • Works across multiple servers for consistency.

Advantages of Learning Shell Scripting

  • Builds confidence with command line.
  • Saves time and prevents errors.
  • Easier transition to other automation tools (Python, Ansible, CI/CD).
  • Practical skill for Linux administration.

Key Takeaway: Shell scripting is not about programming—it’s about working smarter by automating repetitive tasks. For RHCSA, mastering scripting is critical.

Demo 1: Create & Execute First Shell Script

  • Open Terminal: Activities → Terminal icon.
  • Create Script: nano firstscript.sh.
  • Add Shebang: #!/bin/bash (specifies Bash interpreter).
echo "Hello, this is my first shell script in RHEL 9.6"

  • Save & Exit: Ctrl+X, press Y, then Enter.
  • Make Executable: chmod +x firstscript.sh.
  • Run Script:
    • ./firstscript.sh
    • Or bash firstscript.sh.
  • Output: Hello, this is my first shell script in RHEL 9.6.

Demo 2: Variables in Shell Scripts

  • Create Script: nano variables.sh.
  • Add Shebang: #!/bin/bash.
  • Declare Variables:
name="RHEL User"
age=28
  • Use Variables:
echo "Hello, my name is $name and I am $age years old."
  • Save & Exit: Ctrl+X, Y, Enter.
  • Make Executable: chmod +x variables.sh.
  • Run Script: ./variables.sh.
  • Output: Hello, my name is RHEL User and I am 28 years old.
  • Create Script: nano if_basic.sh.
  • Shebang: #!/bin/bash.
  • Prompt & Read Input:
echo "Enter a number:"
read num
  • Condition:
if [ $num -gt 10 ]; then
    echo "Number is greater than 10"
fi
  • Make Executable: chmod +x if_basic.sh.
  • Run: ./if_basic.sh.

if-else Statement

  • Create Script: nano teststatements.sh.
  • Prompt & Read Input:
read -p "Enter your number: " num
  • Condition:
if [ $num -lt 10 ]; then
    echo "$num is less than 10"
else
    echo "$num is greater than 10"
fi
  • Make Executable: chmod +x teststatements.sh.
  • Run: ./teststatements.sh.

if-elif-else Ladder

  • Create Script: nano if_elif.sh.
  • Calculate Disk Usage:
usage=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
  • Conditions:
if [ $usage -lt 50 ]; then
    echo "Disk usage is under control."
elif [ $usage -lt 80 ]; then
    echo "Disk usage is moderate."
else
    echo "Disk usage is critical! Take action."
fi

Demo 1: Basic Debugging with set -x

  • Create Script: nano debug.
#!/bin/bash
set -x  # Enable Debug Mode
echo "Starting Script"
mkdir /tmp/testdir
rm -r /tmp/testdir
set +x   # Turns off debug mode

Demo 2: Safer Script with set -euo pipefail

  • Create Script: nano debug1.sh.
  • Enable Safety Options:
    • set -e → Exit on error.
    • set -u → Treat unset variables as error.
    • set -o pipefail → Fail if any command in pipeline fails.
  • Enable Debug Mode: set -x.
#!/bin/bash

set -euo pipefail
set -x

Directory="/tmp/test"
mkdir -p "$Directory"
cd "$Directory"
touch file1.txt
echo "Script completed"

Key RHCSA Concepts Covered:

  • set -x → Debug mode (prints commands before execution).
  • set +x → Disable debug mode.
  • set -euo pipefail → Makes scripts robust and safe.
  • Using variables and directory operations in scripts.
  • Debugging helps identify errors and execution flow.

What is Advanced Scripting?

  • Goes beyond basic commands and simple logic.
  • Focuses on efficiency, readability, reliability, and flexibility.
  • Scripts behave like real programs: structured, adaptable, and user-friendly.

Key Principles

  • Plan Before Writing:
    • Identify decisions the script must make.
    • Define input types and future flexibility.
  • Think Like a Developer:
    • Design reusable, scalable scripts.
    • Anticipate errors and handle them gracefully.

Core Features of Advanced Scripts

  • Logical Control:
    • Decision trees for multiple outcomes.
    • Validate inputs and handle invalid cases.
  • Environment Awareness:
    • Check disk space, memory, network before actions.
  • Fail-Safes:
    • Recover gracefully from errors.
    • Provide meaningful feedback instead of crashing.

Structure & Flow

  • Use nested conditionals and complex loops with break and continue.
  • Implement flags/switches for customizable behavior.
  • Keep logic organized and readable for long-term maintenance.

User Communication

  • Inform users of actions and errors clearly.
  • Use logging for automated scripts to track events.
  • Provide helpful menus or prompts for invalid inputs.

Error Handling

  • Anticipate missing files, blank inputs, failed commands.
  • Implement backup plans or clear error messages.
  • Ensure scripts remain robust in production environments.

Scalability & Flexibility

  • Design for multiple machines and environments.
  • Support:
    • Environment variables
    • Configuration files
    • Command-line flags
  • Adapt to changing configurations without code changes.

Goal

  • Build scripts that are:
    • Reliable
    • Safe
    • Repeatable
  • Turn scripts into lightweight utilities for enterprise use.

Key RHCSA Takeaway: Advanced scripting is about strategy, not memorizing commands. It’s about creating scripts that anticipate future needs, handle errors gracefully, and adapt to different environments.

Script Overview

  • Goal: Log messages and command outputs with timestamps into a file.

Steps

  1. Create Script:
nano script.sh

2. Add Shebang:

 #!/bin/bash

3. Define Log File Variable:

LOG="/temp/log.txt"

4. Create Logging Function:

 log() {
 echo "$(date '+%F %T') - $1" >> "$LOG"
 }
  • $(date '+%F %T') → Current date and time.
  • $1 → First argument passed to the function.
  • >> "$LOG" → Append to log file.

5. Log Events & Commands:

log "START"
mkdir -p /tmp/demo/file.txt && log "Created file.txt"
ls /tmp/demo >> "$LOG"
log "END"

6. Save & Exit: Ctrl+X, Y, Enter.

7. Make Executable:

chmod +x script.sh

8. Run Script:

./script.sh

9. View Log:

cat /temp/log.txt
  • Output shows each message with timestamp and directory listing.

Key RHCSA Concepts Covered:

  • Using functions in shell scripts.
  • Logging with timestamps for auditing and troubleshooting.
  • Appending output to a file using >>.
  • Combining commands with && for conditional execution.

1. Script Design Principles

  • Plan Before Coding:
    • Define inputs, outputs, and error handling.
    • Anticipate future flexibility (flags, config files).
  • Structure for Readability:
    • Use indentation and comments.
    • Group related logic into functions.

2. Safety & Debugging

  • Enable Safe Mode:
set -euo pipefail
  • -e: Exit on error.
  • -u: Treat unset variables as error.
  • -o pipefail: Fail if any command in pipeline fails.
  • Debug Mode:
set -x    # Enable
set +x    # Disable

3. Variables & Input

  • Declare Variables:
name="RHEL User"
age=28
  • Read Input:
read -p "Enter your choice: " choice

4. Conditional Logic

  • Basic If:
if [ $num -gt 10 ]; then
    echo "Greater than 10"
fi
  • If-Else:
if [ $num -lt 10 ]; then
    echo "Less than 10"
else
    echo "Greater or equal to 10"
fi
  • If-Elif Ladder
if [ $usage -lt 50 ]; then
    echo "Under control"
elif [ $usage -lt 80 ]; then
    echo "Moderate"
else
    echo "Critical"
fi

5. Loops

  • For Loop:
for file in *.txt; do
    echo "Processing $file"
done
  • while loop:
while read line; do
    echo "$line"
done < file.txt
  • Break & Continue:
for i in {1..10}; do
    [ $i -eq 5 ] && continue
    [ $i -eq 8 ] && break
    echo $i
done

6. Functions

  • Define & Call:
myfunc() {
    echo "Hello from function"
}
myfunc

7. Error Handling

  • Check Command Success
if ! command; then
    echo "Command failed"
    exit 1
fi
  • Validate Input:
if [ -z "$input" ]; then
    echo "Input cannot be empty"
    exit 1
fi

8. Logging

  • Redirect Output:
echo "Starting script" >> /var/log/myscript.log
  • Timestamped Logs:
    Show more lines
echo "$(date): Task completed" >> /var/log/myscript.log

9. Flags & Arguments

  • Using $@ and $#:
echo "Total args: $#"
for arg in "$@"; do
    echo "Arg: $arg"
done
  • Case Statement for Options:
case $1 in
    start) echo "Starting service" ;;
    stop) echo "Stopping service" ;;
    *) echo "Usage: $0 {start|stop}" ;;
esac

10. Best Practices

  • Always start with #!/bin/bash.
  • Use quotes around variables: "$var".
  • Validate inputs and environment before execution.
  • Comment your code for clarity.
  • Test with set -x before production use.

Advanced RHCSA Shell Scripting Cheat Sheet

Advanced Scripting Concepts

  • Purpose: Move beyond basic shell scripting (loops, if-else) to create smart, flexible, and reliable scripts.
  • Goal: Scripts should behave like real programs—structured, readable, and adaptable.

Core Principles

  • Planning Before Coding:
    • Identify decisions the script must make.
    • Define expected inputs and future flexibility.
  • Think Like a Developer:
    • Design reusable scripts for others, not just one-off tasks.

Logic & Flow Control

  • Logic is Key:
    • Anticipate errors and changing conditions.
    • Use decision trees for multiple outcomes (e.g., start/stop actions).
  • Environment Awareness:
    • Check disk space, memory, network before proceeding.
  • Fail-safes:
    • Recover gracefully from errors; provide helpful feedback.

Structure & Organization

  • Complex Flow Handling:
    • Use loops with break and continue.
    • Nest conditionals and loops for advanced logic.
  • Flags & Switches:
    • Allow user customization via command-line options.
  • Readability:
    • Keep logic organized for long-term maintainability.

User Communication

  • Interactive & Informative:
    • Scripts should inform users, request input, and explain errors clearly.
  • Logging:
    • Essential for automated scripts; logs show what happened and when.

Error Handling

  • Anticipate Failures:
    • Missing files, invalid input, command failures.
  • Graceful Recovery:
    • Provide clear messages or backup plans.

Scalability & Flexibility

  • Design for Multiple Environments:
    • Handle varying inputs and system configurations.
  • Adaptability:
    • Use environment variables, config files, and flags for easy adjustments.

Key Takeaways

  • Advanced scripting = strategy, not memorization.
  • Focus on:
    • Error handling
    • Adaptability
    • User communication
    • Reusability
  • Aim for scripts that are reliable, safe, and repeatable in production.

Creating a Script with Logging and Timestamps

Objective: To demonstrate the creation of a Bash script that performs system tasks and logs its actions with timestamps. This combines fundamental shell scripting skills with practical system administration.

Key Skills Demonstrated:

  • Creating and executing a Bash script.
  • Using variables and functions.
  • Implementing timestamp-based logging.
  • Using conditional execution (&&).
  • Managing file permissions (chmod).

Demo Walkthrough & Expanded Explanation

Step 1: Creating the Script File

The script is a plain text file containing commands for the shell to execute.

  • Command:bashnano script.sh
  • Explanation: This opens the nano text editor to create a new file named script.sh. The .sh extension is a convention indicating a shell script.

**Step 2: Script Contents and Breakdown

Let’s analyze the script line by line to understand its components.

#!/bin/bash
LOG="/temp/log.txt"
log() {
    echo "$(date '+%F %T')- $1" >> "$LOG"
    }
    
log "start"
mkdir -p /tmp/demo && log "Created /tmp/demo"
touch /tmp/demo/file.txt && log "Created file.txt"
ls /tmp/demo >> "$LOG"
log "END"
Function Definition: This defines a reusable function named log.
  • $(date '+%F %T') executes the date command in a subshell. The format %F gives the full date (e.g., 2023-10-05) and %T gives the time (e.g., 14:30:22).
  • $1 represents the first argument passed to the function (the message to log).
  • >> "$LOG" appends the output to the file specified by the LOG variable. Using >> ensures previous log entries are not overwritten
log "start"
  • Function Call: 
    • Calls the log function and passes the string "start" as its argument. This will be the value of $1 inside the function.
  • Conditional Execution (&&):
    • mkdir -p /tmp/demo creates the directory. The -p flag prevents errors if the directory already exists.
    • && means “if and only if the previous command succeeded (returned exit status 0), then execute the next command.”
    • log "Created /tmp/demo" logs a success message. This will only run if the mkdir command was successful.

Leave a Reply

Your email address will not be published. Required fields are marked *