Scripting Techniques
Introduction to Shell Scripting
Bash Scripting Basics
#!/bin/bash
## Basic script structure
## Variables
name="LabEx"
echo "Welcome to $name"
graph TD
A[Shell Scripting] --> B[Variables]
A --> C[Conditionals]
A --> D[Loops]
A --> E[Functions]
Script Execution Permissions
## Make script executable
chmod +x script.sh
## Run script
./script.sh
Control Structures
Conditional Statements
#!/bin/bash
## Conditional example
if [ $value -gt 10 ]; then
echo "Value is greater than 10"
elif [ $value -eq 10 ]; then
echo "Value is equal to 10"
else
echo "Value is less than 10"
fi
Loop Structures
## For loop
for i in {1..5}; do
echo "Iteration $i"
done
## While loop
counter=0
while [ $counter -lt 5 ]; do
echo $counter
((counter++))
done
Function Definition
## Function example
system_info() {
echo "Hostname: $(hostname)"
echo "OS: $(uname -s)"
echo "Kernel: $(uname -r)"
}
## Call function
system_info
Advanced Scripting Techniques
#!/bin/bash
## User input and validation
read -p "Enter your name: " username
if [ -z "$username" ]; then
echo "Name cannot be empty"
exit 1
fi
Error Handling
## Error handling
command_that_might_fail || {
echo "Command failed"
exit 1
}
Scripting Best Practices
Practice |
Description |
Example |
Shebang |
Specify interpreter |
#!/bin/bash |
Comments |
Explain code |
## This is a comment |
Error Checking |
Validate inputs |
[ -f file ] && process_file |
Practical Script Examples
System Backup Script
#!/bin/bash
## Simple backup script
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d)
mkdir -p $BACKUP_DIR
tar -czvf $BACKUP_DIR/system_backup_$DATE.tar.gz /home /etc
Log Rotation Script
#!/bin/bash
## Basic log rotation
LOG_FILE="/var/log/myapp.log"
MAX_LOGS=5
if [ $(wc -l < $LOG_FILE) -gt 1000 ]; then
mv $LOG_FILE "$LOG_FILE.1"
touch $LOG_FILE
find /var/log -name "myapp.log.*" | sort -r | tail -n +$((MAX_LOGS+1)) | xargs rm
fi
LabEx Scripting Tips
- Always test scripts in safe environments
- Use
set -e
to exit on errors
- Implement logging for complex scripts
Conclusion
Mastering shell scripting techniques empowers Linux administrators to automate tasks, improve efficiency, and solve complex system management challenges.