Domain 3Shell ScriptingCORE

Create simple shell scripts

Bash scripting fundamentals, environment variables, command substitution, exit codes, test conditions, if/case logic, and loops for automation.

Domain: Domain 3: Create simple shell scripts•Updated: 2026-08-29
#Bash#Shell Scripting#Automation#Variables#Loops#Conditionals

RHCSA Chapter 3: Scripting — Commands Reference

Source Material: Chapter 07 (The Bash Shell), Chapter 19 (Automation with Bash Shell Scripting), Chapter 22 (Shell Scripting) Output Location: D:\ai\commands\03_Scripting_Commands.md


Table of Contents

  1. Script Creation and Execution
  2. Variables
  3. Command and Variable Substitution
  4. Input/Output/Error Redirection
  5. Pipes and Pipelines
  6. History Substitution
  7. Tilde Substitution
  8. Alias Substitution
  9. Metacharacters and Wildcards
  10. Quoting Mechanisms
  11. Regular Expressions and grep
  12. Job Control
  13. Shell Parameters
  14. Exit Codes
  15. Test Conditions
  16. Logical Constructs — if/then/else/case
  17. Logical Shortcuts — && and ||
  18. Looping Constructs
  19. Script Debugging
  20. Shell Startup Files
  21. System Information Commands
  22. Quick-Reference Summary Table

1. Script Creation and Execution

Shebang

Every Bash script must start with a shebang to specify the interpreter:

#!/bin/bash

Other shells can also be specified (e.g., #!/usr/bin/perl).

Making a Script Executable

chmod +x script.sh

Running a Script

./script.sh          # Run from current directory (requires execute permission)
bash script.sh       # Run as argument to bash (no execute permission needed)
/usr/local/bin/script.sh  # Run by full path

Note: The /usr/local/bin directory is included in all users’ $PATH by default — a good location for scripts.

Script Comments

# This is a comment — ignored during execution

2. Variables

Local (Shell) Variables

Private to the current shell; not inherited by subshells.

VR1="value"
NAME="John"

Environment Variables

Inherited by child processes and subshells.

export VR1="value"
export VAR1="I passed RHCSA"

Viewing Variables

echo $VR1            # View a specific variable
echo $PATH           # View PATH variable
echo $HOME           # View HOME variable
echo $SHELL          # View SHELL variable
echo $TERM           # View TERM variable
echo $PPID           # View parent process ID
echo $PS1            # View primary prompt
echo $USER           # View current user
echo $LOGNAME        # View login name
echo $PWD            # View current directory
echo $UID            # View user ID
echo $DISPLAY        # View display hostname/IP
echo $MAIL           # View mail directory path
echo $HISTFILE       # View history file location
echo $HISTSIZE       # View history size in memory
echo $HISTFILESIZE   # View history file max size

env                  # Display all environment variables
printenv             # Display all environment variables
set                  # Display all local AND environment variables

Unsetting Variables

unset VR1
unset VAR1

Defining Variables with Spaces

VR2="value with spaces"

Common Predefined Environment Variables

Variable Description
DISPLAY Hostname or IP for graphical terminal sessions
HISTFILE File for storing command history (default: ~/.bash_history)
HISTSIZE Max commands held in memory for current session
HISTFILESIZE Max commands stored in history file
HOME Home directory path
LOGNAME Login name
MAIL Path to user mail directory
PATH Colon-separated list of directories for command search
PPID Parent process identifier
PS1 Primary command prompt
PS2 Secondary command prompt
PWD Current directory location
SHELL Absolute path to primary shell file
TERM Terminal type value
UID Logged-in user’s UID
USER Logged-in user’s name

Dynamic Variable Definition

TODAY=$(date +%d-%m-%y)    # Command substitution (preferred)
TODAY=`date +%d-%m-%y`     # Command substitution (legacy backtick syntax)

Reading User Input

read NAME
read -p "Enter name: " USERNAME

3. Command and Variable Substitution

Command Substitution

Capture the output of a command into a variable:

HOSTNAME_VAR=$(hostname)       # Preferred syntax
HOSTNAME_VAR=`hostname`        # Legacy backtick syntax
SYSINFO=$(uname -a)

Variable Substitution

Reference a variable’s value with $:

echo $LOGNAME
echo $PWD
echo $HOME

Customizing PS1 Prompt

PS1="< $LOGNAME on $(hostname) in $PWD >: "

PS1 escape sequences:

  • \u — logged-in username
  • \h — hostname
  • \W — current working directory (short form)
  • \$ — end of prompt (# for root, $ for normal users)

4. Input/Output/Error Redirection

Standard Input (stdin — file descriptor 0)

cat < /etc/redhat-release    # Read input from file instead of keyboard

Standard Output (stdout — file descriptor 1)

ls > ls.out                  # Overwrite file with stdout
ls 1> ls.out                 # Same as above (explicit file descriptor)
ls >> ls.out                 # Append stdout to file
ls 1>> ls.out                # Same as above (explicit file descriptor)

Standard Error (stderr — file descriptor 2)

find / -name core 2> /dev/null        # Send errors to /dev/null (discard)
find / -name core 2> /tmp/errors.txt  # Send errors to a file

Redirecting Both stdout and stderr

ls /usr /cdr &> outerr.out     # Both to file (overwrite)
ls /usr /cdr &>> outerr.out    # Both to file (append)
ls /usr /cdr 1> outerr.out 2>&1  # Equivalent: stdout to file, stderr follows stdout

Preventing Accidental Overwrite (noclobber)

set -o noclobber    # Enable — prevents > from overwriting existing files
set +o noclobber    # Disable

/dev/null

The “black hole” — discards all data sent to it:

command > /dev/null 2>&1    # Discard both stdout and stderr
ping -c 1 10.0.0.20 2>/dev/null    # Discard ping errors

5. Pipes and Pipelines

Pipe Operator

Sends stdout of one command as stdin to the next:

ls /etc | less                    # View directory listing page by page
last | nl                         # Number each line of login history
ls | grep -v "root"               # Exclude lines containing "root"

Pipeline (Multiple Pipes)

ls | grep -v "root" | grep -iv "dec" | nl | tail -4

6. History Substitution

Viewing History

history                    # Display all history entries
history 10                 # Display current + 10 preceding entries

Re-executing Commands

!15                        # Re-execute command at line 15
!ch                        # Re-execute most recent command starting with "ch"
!grep                      # Re-execute most recent command containing "grep"
!!                         # Re-execute the last command

Managing History

history -d 24              # Remove entry 24 from history

Enabling/Disabling History

set +o history    # Disable history expansion
set -o history    # Re-enable history expansion

History Variables

echo $HISTFILE       # Default: ~/.bash_history
echo $HISTSIZE       # Max commands in memory
echo $HISTFILESIZE   # Max commands in history file

7. Tilde Substitution

~                    # Expands to current user's $HOME
~+                   # Expands to current directory
~-                   # Expands to previous working directory
~user1               # Expands to user1's $HOME directory

Usage with Commands

cd ~user1            # Change to user1's home directory
ls -ld ~root/Desktop # List root's Desktop directory
cd ~user1/dir1       # Change to subdirectory of user1's home

8. Alias Substitution

Viewing Aliases

alias                # List all currently defined aliases

Predefined Aliases (examples)

Alias Value Definition
vi vim Runs vim instead of vi
cp cp -i Copy in interactive mode
ll ls -l Long format listing
mv mv -i Move in interactive mode
rm rm -i Remove in interactive mode
which which --tty-only --read-alias --read-functions --show-tilde --show-dot Enhanced which

Creating Aliases

alias search='find / -name core -type f 2>/dev/null'
alias rm='rm -i'

Bypassing an Alias

\rm file.txt         # Backslash forces the actual rm command, not the alias

Removing Aliases

unalias search
unalias rm
unalias search rm    # Remove multiple aliases

9. Metacharacters and Wildcards

Asterisk (*)

Matches zero to unlimited characters (except leading . in hidden files):

ls /etc/ma*                    # Files starting with "ma"
ls /home/user1/.*              # Hidden files and directories
ls /var/log/*.log              # Files ending in ".log"

Question Mark (?)

Matches exactly one character (except leading .):

ls /var/log/????               # Names with exactly 4 characters

Square Brackets []

Match a set or range of characters for a single position:

ls /etc/[xyz]*                 # Names starting with x, y, or z
ls /etc/systemd/system/[m-o]*  # Names starting with m, n, or o
ls /etc/[a-z]*                 # Names starting with any lowercase letter
ls /etc/[0-9]*                 # Names starting with any digit

Exclamation Mark (!) — Inverse Match

ls /etc/systemd/system/[!m-o]* # Names NOT starting with m, n, or o
ls [!a-d]*                     # Names NOT starting with a, b, c, or d

Other Metacharacters

$ ^ . * ? | < > { } [ ] ( ) + ! ; \


10. Quoting Mechanisms

Backslash () — Escape Character

Masks the meaning of the single character that follows:

rm \*                         # Remove a file literally named "*"
echo "Price is \$100"         # Print literal dollar sign
echo "I do not know what \$1 is"  # Print literal $1

Single Quotes (’ ’)

Treats ALL enclosed characters as literal — no variable expansion, no command substitution:

echo '$LOGNAME'               # Prints literal "$LOGNAME", not the value
echo 'Hello $USER'            # Prints "Hello $USER" literally

Double Quotes (” “)

Allows variable expansion ($VAR) and command substitution ($(cmd)), but masks most other special characters. The \, $, and ` retain special meaning inside double quotes:

echo "Hello $USER"            # Prints "Hello" followed by the actual username
echo "Today is $(date)"       # Prints today's date
echo "Price is \$100"         # Prints "Price is $100"

11. Regular Expressions and grep

grep Command

Searches text for pattern matches:

grep "operator" /etc/passwd                           # Search for pattern
grep "aliases and functions" ~/.bashrc                # Search multi-word pattern (in quotes)
grep -v "nologin" /etc/passwd                         # Exclude lines with pattern
grep -n -v "nologin" /etc/passwd                    # Show line numbers + exclude
grep "^root" /etc/passwd                              # Lines starting with "root"
grep "bash$" /etc/passwd                              # Lines ending with "bash"
grep -v "^$" /etc/login.defs                          # Exclude empty lines
grep -i "path" /etc/bashrc                            # Case-insensitive search
grep -w "acce.." /etc/lvm/lvm.conf                    # Whole word match
grep -E "cron|ly" /etc/                               # Extended regex — alternation (OR)
grep -v -e "^$" -e "^#" /etc/ssh/sshd_config          # Exclude empty lines AND comments

grep Options

Option Description
-i Case-insensitive search
-v Invert match (exclude matching lines)
-n Show line numbers
-w Whole word match
-E Extended regular expressions (enables |, +, ?, {})
-e Specify pattern (can use multiple times)

Regular Expression Metacharacters

Character Meaning
^ Start of line
$ End of line
. Any single character
* Zero or more of preceding character
? Exactly one character (in glob); zero or one (in regex with -E)
[] Character set / range
{} Repetition count (with -E)
| Alternation / OR (with -E)

Additional grep Resources

man 7 regex              # Learn more about regular expressions
man grep                 # Full grep documentation

12. Job Control

Running in Background

top &                    # Start top in background
vim testfile1 &          # Start vim in background

Managing Jobs

jobs                     # List background jobs
jobs -l                  # List jobs with PIDs
fg %1                    # Bring job 1 to foreground
bg %1                    # Resume suspended job 1 in background
Ctrl+z                   # Suspend current foreground job
kill 31726               # Terminate process by PID
kill -9 1234             # Force kill process by PID

Job Indicators

  • + — Current (most recent) background job
  • - — Previous background job
  • “Stopped” — Job is suspended

13. Shell Parameters

Positional Parameters

Arguments supplied when invoking a script:

$1                       # First argument
$2                       # Second argument
$3                       # Third argument
${10}                    # Tenth argument (braces required for 10+)

Special Parameters

$0                       # Script name itself
$#                       # Total count of arguments
$@                       # All arguments (preserves individual quoting)
$*                       # All arguments (as single string)
$$                       # PID of current script/process
$?                       # Exit code of last command

Shift Command

Move positional parameters left:

shift                    # Shift left by 1 ($2 becomes $1, $1 is lost)
shift 2                  # Shift left by 2
shift 3                  # Shift left by 3

14. Exit Codes

Checking Exit Codes

echo $?                  # Display exit code of last command
  • 0 — Success
  • Non-zero — Failure (specific values indicate different error types)

Setting Exit Codes in Scripts

exit 0                   # Script completed successfully
exit 1                   # Script failed (generic error)
exit 2                   # Script failed (specific error code)

15. Test Conditions

test Command / [ ] Syntax

test -f /etc/hosts       # Test if file exists
[ -f /etc/hosts ]        # Equivalent using brackets

CRITICAL: Spaces are mandatory inside brackets: [ -f $1 ] NOT [-f $1]

Integer Comparisons

Operator Description
-eq Equal
-ne Not equal
-lt Less than
-gt Greater than
-le Less than or equal
-ge Greater than or equal
[ $1 -gt 0 ]             # Is argument greater than 0?
[ $COUNT -eq 5 ]         # Is COUNT equal to 5?

String Comparisons

Operator Description
= Strings are identical
!= Strings are not identical
-z string String length is zero (empty)
-n string String length is non-zero (not empty)
[ -z $1 ]                # Is $1 empty?
[ "$1" = "ex200" ]       # Does $1 equal "ex200"?
[ "$1" != "ex294" ]      # Does $1 NOT equal "ex294"?

File Tests

Operator Description
-b file File is a block device
-c file File is a character device
-d file File is a directory
-f file File is a regular file
-e file File exists
-s file File exists and is non-empty
-L file File is a symbolic link
-r file File is readable
-w file File is writable
-x file File is executable
-u file File has setuid bit set
-g file File has setgid bit set
-k file File has sticky bit set
file1 -nt file2 file1 is newer than file2
file1 -ot file2 file1 is older than file2

Logical Operators

Operator Description
! Logical NOT
-a or && Logical AND
-o or || Logical OR
[ -b file1 -a -r file1 ]     # file1 is block device AND readable
[ $x -eq 1 -o $y -eq 2 ]     # x equals 1 OR y equals 2

16. Logical Constructs — if/then/else/case

if-then-fi

if [ condition ]
then
    action
fi

Example:

if [ $# -ne 2 ]
then
    echo "Error: Provide exactly 2 arguments"
    exit 2
fi

if-then-else-fi

if [ condition ]
then
    action1
else
    action2
fi

Example:

if [ $1 -gt 0 ]
then
    echo "Positive"
else
    echo "Negative or zero"
fi

if-then-elif-else-fi

if [ condition1 ]
then
    action1
elif [ condition2 ]
then
    action2
elif [ condition3 ]
then
    action3
else
    action_n
fi

Example:

if [ -f $1 ]
then
    echo "$1 is a file"
elif [ -d $1 ]
then
    echo "$1 is a directory"
else
    echo "I do not know what $1 is"
fi

Semicolon Shorthand

if [ -z $1 ]; then
    echo "no value provided"
fi

case Statement

case "$1" in
    start)
        echo "Starting"
        ;;
    stop)
        rm -f $lockfile
        echo "Stopping"
        ;;
    restart)
        echo "Restarting"
        ;;
    reload)
        echo "Reloading"
        ;;
    status)
        echo "Status"
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|status}"
        ;;
esac

The *) is a catch-all for any value not matched. Each case ends with ;;. The construct closes with esac.


17. Logical Shortcuts — && and ||

AND (&&)

Execute second command only if first succeeds:

[ -f /etc/hosts ] && echo "File exists"
[ -z $1 ] && echo "No argument provided"
ping -c 1 192.168.4.$i > /dev/null && echo "192.168.4.$i is up"

OR (||)

Execute second command only if first fails:

ping -c 1 10.0.0.20 2>/dev/null || echo "Node is not available"

18. Looping Constructs

for Loop — List Iteration

for VAR in list
do
    action
done

Examples:

for user in alice bob charlie; do useradd $user; done
for LETTER in {A..Z}; do echo $LETTER; done
for i in $@; do echo $i; done
for i in {100..104}; do ping -c 1 192.168.4.$i > /dev/null && echo "192.168.4.$i is up"; done

for Loop — C-Style Arithmetic

for (( COUNTER=100; COUNTER>1; COUNTER-- ))
do
    echo $COUNTER
done

One-liner:

for (( COUNTER=100; COUNTER>1; COUNTER-- )); do echo $COUNTER; done

while Loop

Execute as long as condition is true:

while [ condition ]
do
    action
done

Examples:

while [ -f /tmp/lock ]; do sleep 5; done

while ps aux | grep $1 | grep -v grep > ~/output
do
    sleep 5
done
clear
echo "Your process has stopped"
logger "$1 is no longer present"

until Loop

Execute until condition becomes true:

until [ condition ]
do
    action
done

Examples:

until ping -c 1 192.168.1.1 > /dev/null; do sleep 5; done

until users | grep $1 > /dev/null
do
    echo "$1 is not logged in yet"
    sleep 5
done
echo "$1 has just logged in"

Arithmetic Operators in Loops

Operator Description
! Negation
+ - * / Addition, subtraction, multiplication, division
% Remainder
< <= Less than, less than or equal
> >= Greater than, greater than or equal
= Assignment
== != Equality, non-equality

let and expr Commands

let COUNT=COUNT+1          # Increment variable
COUNT=$(expr $COUNT + 1)   # Increment using expr

break and continue

break                      # Exit the current loop immediately
continue                   # Skip to next iteration of the loop

sleep Command

sleep 5                    # Pause execution for 5 seconds

19. Script Debugging

Debug Mode

bash -x script.sh                          # Run script in debug mode

Or modify the shebang:

#!/bin/bash -x

The debug output shows each line prefixed with + before execution, along with expanded variable values.


20. Shell Startup Files

System-Wide Startup Files

File Purpose
/etc/profile Sets environment variables (PATH, USER, LOGNAME, MAIL, HOSTNAME, HISTSIZE, HISTCONTROL); sets umask for login shells; sources /etc/profile.d/*.sh
/etc/bashrc Defines functions and aliases; sets umask for non-login shells; establishes command prompt
/etc/profile.d/ Directory containing scripts sourced by /etc/profile

Per-User Startup Files

File Purpose
~/.bash_profile Sets environment variables; sources ~/.bashrc; executed for login shells
~/.bashrc Defines functions and aliases; sources /etc/bashrc; executed for interactive non-login shells
~/.bash_logout Executed when user logs off
~/.bash_history Stores command history
~/.gnome2/ GNOME desktop environment settings (if GNOME installed)

Execution Order

  1. /etc/profile (system-wide, first)
  2. ~/.bash_profile (per-user login)
  3. ~/.bashrc (per-user interactive)
  4. /etc/bashrc (system-wide, last)

21. System Information Commands

hostnamectl                # Display hostname, platform, OS, kernel, architecture
who                        # List currently logged-in users
hostname                   # Display system hostname
uname -a                   # Display all system information
date +%d-%m-%y             # Display current date in DD-MM-YY format
users                      # List currently logged-in usernames
ps aux                      # List all running processes
nl file.txt                # Number lines of a file
clear                      # Clear terminal screen

Additional Commands Referenced in Labs

useradd <username>         # Create a new user account
passwd <username>          # Set/change user password
parted                     # Partition disk management tool
pvcreate                   # Create LVM physical volume
mail -s "subject" root     # Send email to root with subject
mail -s "Error" root < log.txt   # Send file content as email body
logger "message"           # Write message to system log

22. Quick-Reference Summary Table

Command / Construct Syntax / Example Purpose
#!/bin/bash First line of script Shebang — specifies interpreter
chmod +x chmod +x script.sh Add execute permission
bash -x bash -x script.sh Run script in debug mode
echo echo "Text $VAR" Print text/variables to stdout
export export VAR="value" Promote to environment variable
unset unset VAR Delete a variable
env / printenv env Display environment variables
set set -o noclobber View all variables / toggle options
read read -p "Prompt: " VAR Read user input
shift shift 2 Shift positional parameters left
test / [ ] [ -f /etc/hosts ] Evaluate conditions
exit exit 1 Terminate script with exit code
grep grep -i "^root" /etc/passwd Pattern matching in text
alias alias ll='ls -la' Create command shortcut
unalias unalias ll Remove an alias
history history | tail -n 10 View/re-run command history
jobs jobs -l List background jobs
bg / fg bg %1 / fg %1 Move job to background/foreground
kill kill -9 1234 Terminate process by PID
mail mail -s "Error" root < log.txt Send email
logger logger "message" Write to system log
sleep sleep 5 Pause execution (seconds)
hostnamectl hostnamectl Display system information
who who List logged-in users
ps aux ps aux | grep process List/filter running processes
> cmd > file Redirect stdout (overwrite)
>> cmd >> file Redirect stdout (append)
2> cmd 2> file Redirect stderr
&> cmd &> file Redirect both stdout and stderr
2>&1 cmd > file 2>&1 Send stderr to same place as stdout
< cmd < file Redirect stdin from file
| cmd1 | cmd2 Pipe stdout to next command’s stdin
&& cmd1 && cmd2 Run cmd2 only if cmd1 succeeds
|| cmd1 || cmd2 Run cmd2 only if cmd1 fails
$(cmd) VAR=$(hostname) Command substitution
`cmd` VAR=`hostname` Command substitution (legacy)
if/then/fi if [ cond ]; then action; fi Conditional execution
if/elif/else/fi Multiple conditions Multi-branch conditional
case/esac case "$1" in start) ... ;; esac Pattern-based branching
for/do/done for i in {1..10}; do ...; done Loop over list/range
while/do/done while [ cond ]; do ...; done Loop while condition true
until/do/done until [ cond ]; do ...; done Loop until condition true
~ ~user1 Tilde expansion to home directory
& `cmd &`` Run command in background
Ctrl+z Key combo Suspend foreground job
!! !! Re-execute last command
!n !15 Re-execute history line n
$? echo $? Exit code of last command
$# echo $# Number of arguments
$@ / $* for i in $@; do ... All arguments
$$ echo $$ Current process PID
$0 echo $0 Script name