Chapter 10: Linux Shell Scripting

45 min read ▅▅ Advanced 📅 Updated July 2026

Learning Objectives

  • Understand Shell Scripting[cite: 22].
  • Differentiate common Linux shells[cite: 22].
  • Create and execute Bash scripts[cite: 22].
  • Use variables and environment variables[cite: 22].
  • Read user input[cite: 22].
  • Work with command-line arguments[cite: 22].
  • Understand exit status[cite: 22].

What is Shell Scripting?

A shell script is a text file containing Linux commands executed sequentially by a shell interpreter[cite: 22]. Shell scripting automates repetitive administrative tasks and improves efficiency[cite: 22].

🏢 Enterprise Insight

Linux administrators use shell scripts for backups, monitoring, patching, health checks, log cleanup and user management[cite: 22].

Shell Architecture

User ──► Shell (bash) ──► Linux Kernel ──► Hardware[cite: 22]
              

Common Linux Shells

ShellDescription
shBourne Shell[cite: 22]
bashBourne Again Shell (Default)[cite: 22]
kshKorn Shell (Common on AIX)[cite: 22]
zshAdvanced interactive shell[cite: 22]
fishFriendly Interactive Shell[cite: 22]

Your First Script

touch hello.sh
vi hello.sh
#!/bin/bash
echo "Welcome to Linux Shell Scripting"[cite: 22]

Run a Script

chmod +x hello.sh
./hello.sh
bash hello.sh
sh hello.sh

Understanding the Shebang

#!/bin/bash

The shebang tells Linux which interpreter should execute the script[cite: 22].

Comments

# This is a comment

Comments improve readability and maintenance[cite: 22].

Variables

NAME="Ashutosh"
echo $NAME

Best Practice

Do not place spaces around the '=' operator while assigning variables[cite: 22].

Environment Variables

echo $HOME
echo $USER
echo $PATH
echo $SHELL
env
VariableDescription
HOMEUser home directory[cite: 22]
USERCurrent user[cite: 22]
PATHExecutable search path[cite: 22]
SHELLCurrent shell[cite: 22]

User Input

read NAME
echo "Welcome $NAME"[cite: 22]

Command-Line Arguments

./script.sh John Delhi
ParameterMeaning
$0Script name[cite: 22]
$1First argument[cite: 22]
$2Second argument[cite: 22]
$#Argument count[cite: 22]
$@All arguments[cite: 22]

Exit Status

ls /tmp
echo $?

Exit code 0 indicates success[cite: 22]. Any non-zero value indicates an error[cite: 22].

Command Substitution

TODAY=$(date)
HOST=$(hostname)
echo $TODAY
echo $HOST

Arithmetic

A=10
B=20
echo $((A+B))
echo $((A-B))
echo $((A*B))
echo $((A/B))

Useful Commands

echo
printf
pwd
hostname
whoami
date
clear
exit

Production Example

#!/bin/bash
echo "Hostname : $(hostname)"
echo "User     : $(whoami)"
echo "Date     : $(date)"
echo "Uptime   : $(uptime -p)"[cite: 22]

Hands-on Practice

  1. Create your first Bash script[cite: 22].
  2. Display today's date and print hostname[cite: 22].
  3. Accept user input and use command-line arguments[cite: 22].
  4. Display HOME and PATH variables[cite: 22].
  5. Perform arithmetic calculations[cite: 22].

⚠ Common Mistakes

  • Forgetting the shebang[cite: 22].
  • Not making the script executable[cite: 22].
  • Using spaces around '='[cite: 22].
  • Missing quotes around values with spaces[cite: 22].
  • Using the wrong interpreter[cite: 22].

Decision Making

Conditional statements allow a script to perform different actions based on conditions[cite: 22].

if Statement

#!/bin/bash
AGE=20
if [ $AGE -ge 18 ]
then
  echo "Eligible"
fi

if...else

MARKS=45
if [ $MARKS -ge 50 ]
then
  echo "Pass"
else
  echo "Fail"
fi

if...elif...else

SCORE=82
if [ $SCORE -ge 90 ]; then
  echo "Grade A"
elif [ $SCORE -ge 75 ]; then
  echo "Grade B"
else
  echo "Grade C"
fi

Comparison Operators

OperatorMeaning
-eqEqual[cite: 22]
-neNot Equal[cite: 22]
-gtGreater Than[cite: 22]
-geGreater Than or Equal[cite: 22]
-ltLess Than[cite: 22]
-leLess Than or Equal[cite: 22]

String Comparisons

NAME="linux"
if [ "$NAME" = "linux" ]
then
  echo "Matched"
fi
OperatorDescription
=Equal[cite: 22]
!=Not Equal[cite: 22]
-zEmpty String[cite: 22]
-nNot Empty[cite: 22]

case Statement

read OPTION
case $OPTION in
1) echo "Start";;
2) echo "Stop";;
3) echo "Restart";;
*) echo "Invalid";;
esac

🏢 Production Insight

case statements are commonly used in service management and menu-driven administration scripts[cite: 22].

Looping Constructs (for, while, until)

for Loop

for USER in user1 user2 user3
do
  echo $USER
done

while Loop

COUNT=1
while [ $COUNT -le 5 ]
do
  echo $COUNT
  COUNT=$((COUNT+1))
done

Loop Controls (break, continue)

# break example
for i in {1..10}; do
  [ $i -eq 5 ] && break
  echo $i
done

# continue example
for i in {1..5}; do
  [ $i -eq 3 ] && continue
  echo $i
done

Functions & Reusable Blocks

greet() {
  echo "Welcome $1"
}
greet "Linux"

File Tests

TestDescription
-fRegular file[cite: 22]
-dDirectory[cite: 22]
-rReadable[cite: 22]
-wWritable[cite: 22]
-xExecutable[cite: 22]
-eExists[cite: 22]

Text Processing inside Scripts (grep, awk, sed, cut)

grep root /etc/passwd              # Search patterns[cite: 22]
cut -d: -f1 /etc/passwd             # Column slice segregation[cite: 22]
awk -F: '{print $1,$3}' /etc/passwd # Advanced field reports[cite: 22]
sed 's/error/ERROR/g' app.log       # Stream modification edits[cite: 22]

Debugging Shell Scripts

bash -x script.sh    # Trace script execution lines[cite: 22]
bash -n script.sh    # Check syntax flags only[cite: 22]
set -e               # Instruct script to exit immediately upon failure[cite: 22]

Scheduling Tasks with Cron

crontab -e
0 2 * * * /opt/scripts/backup.sh   # Run daily at 2:00 AM[cite: 22]

Production Script Example - Disk Usage Monitor

#!/bin/bash
THRESHOLD=80

df -h | awk 'NR>1 {print $5,$6}' | while read USE MOUNT
do
 VALUE=${USE%%%}
 if [ $VALUE -ge $THRESHOLD ]; then
   echo "Warning: $MOUNT is ${VALUE}% full"
 fi
done

Commands Covered in This Chapter

  • bash -n / bash -x - Syntax validation and statement execution tracing[cite: 22]
  • set -e / set -x - Environment constraint modifiers and shell debugging switches[cite: 22]
  • crontab - Schedule persistent system and administrative background routines[cite: 22]
  • grep / awk / sed / cut - Structural stream processing and text parsers[cite: 22]
  • useradd / id - System account allocation trackers[cite: 22]
  • df - Core storage partition capacity inspector[cite: 22]