Shell Scripting Essentials
Shell Script Fundamentals
Shell scripting enables automation and complex system interactions through programmatic command execution. Scripts provide a powerful method for streamlining Linux system tasks.
Basic Script Structure
#!/bin/bash
## Shebang line specifies the interpreter
## Variable declaration
NAME="Ubuntu"
VERSION=22.04
## Function definition
greet() {
echo "Welcome to $NAME $VERSION"
}
## Main script logic
main() {
greet
date
}
## Execute main function
main
Script Execution Modes
Execution Method |
Command |
Description |
Direct Execution |
./script.sh |
Requires executable permissions |
Bash Interpreter |
bash script.sh |
Runs without changing permissions |
Source Command |
source script.sh |
Executes in current shell context |
graph TD
A[Shell Script] --> B{Execution Method}
B --> |Direct| C[chmod +x script.sh]
B --> |Interpreter| D[bash script.sh]
B --> |Source| E[source script.sh]
Control Structures
Conditional Statements
## If-else example
if [ $VALUE -gt 10 ]; then
echo "Value is greater than 10"
else
echo "Value is less than or equal to 10"
fi
## Case statement
case $OPTION in
start)
echo "Starting service"
;;
stop)
echo "Stopping service"
;;
*)
echo "Invalid option"
;;
esac
Loop Structures
## For loop
for item in {1..5}; do
echo "Iteration: $item"
done
## While loop
counter=0
while [ $counter -lt 5 ]; do
echo "Counter: $counter"
((counter++))
done
## User input
read -p "Enter your name: " username
echo "Hello, $username!"
## Command substitution
current_date=$(date)
system_uptime=$(uptime)
Script Error Handling
## Exit on error
set -e
## Check command success
if ! command; then
echo "Command failed"
exit 1
fi
Advanced Script Techniques
graph LR
A[Shell Script] --> B[Variables]
A --> C[Functions]
A --> D[Control Structures]
A --> E[Error Handling]
A --> F[System Interaction]