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
| Shell | Description |
|---|---|
| sh | Bourne Shell[cite: 22] |
| bash | Bourne Again Shell (Default)[cite: 22] |
| ksh | Korn Shell (Common on AIX)[cite: 22] |
| zsh | Advanced interactive shell[cite: 22] |
| fish | Friendly 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
| Variable | Description |
|---|---|
| HOME | User home directory[cite: 22] |
| USER | Current user[cite: 22] |
| PATH | Executable search path[cite: 22] |
| SHELL | Current shell[cite: 22] |
User Input
read NAME
echo "Welcome $NAME"[cite: 22]
Command-Line Arguments
./script.sh John Delhi
| Parameter | Meaning |
|---|---|
| $0 | Script name[cite: 22] |
| $1 | First argument[cite: 22] |
| $2 | Second 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
- Create your first Bash script[cite: 22].
- Display today's date and print hostname[cite: 22].
- Accept user input and use command-line arguments[cite: 22].
- Display HOME and PATH variables[cite: 22].
- 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
| Operator | Meaning |
|---|---|
| -eq | Equal[cite: 22] |
| -ne | Not Equal[cite: 22] |
| -gt | Greater Than[cite: 22] |
| -ge | Greater Than or Equal[cite: 22] |
| -lt | Less Than[cite: 22] |
| -le | Less Than or Equal[cite: 22] |
String Comparisons
NAME="linux"
if [ "$NAME" = "linux" ]
then
echo "Matched"
fi
| Operator | Description |
|---|---|
| = | Equal[cite: 22] |
| != | Not Equal[cite: 22] |
| -z | Empty String[cite: 22] |
| -n | Not 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
| Test | Description |
|---|---|
| -f | Regular file[cite: 22] |
| -d | Directory[cite: 22] |
| -r | Readable[cite: 22] |
| -w | Writable[cite: 22] |
| -x | Executable[cite: 22] |
| -e | Exists[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]