Shell Scripting
Learn how to write and use shell scripts in Linux for automation and system administration.
Shell Scripting
Shell scripting is a powerful way to automate tasks and create system administration tools in Linux. This guide covers the basics and advanced concepts of shell scripting.
Shell Script Basics
Creating a Script
Basic script structure:
#!/bin/bash
# Script name: example.sh
# Description: Basic shell script example
# Variables
NAME="World"
# Main script
echo "Hello, $NAME!"
Script Permissions
chmod +x script.sh # Make script executable
./script.sh # Run the script
Variables and Data Types
Variable Declaration
# String variables
NAME="John"
# Numeric variables
AGE=25
# Array variables
FRUITS=("apple" "banana" "orange")
Variable Usage
echo $NAME # Print variable
echo ${NAME} # Print variable (braces)
echo "${NAME} is $AGE years old" # String interpolation
Control Structures
Conditional Statements
# If statement
if [ $AGE -ge 18 ]; then
echo "Adult"
else
echo "Minor"
fi
# Case statement
case $FRUIT in
"apple")
echo "Red fruit"
;;
"banana")
echo "Yellow fruit"
;;
*)
echo "Unknown fruit"
;;
esac
Loops
# For loop
for i in {1..5}; do
echo "Number: $i"
done
# While loop
while [ $COUNTER -lt 10 ]; do
echo $COUNTER
((COUNTER++))
done
Functions
Function Definition
# Basic function
function greet() {
echo "Hello, $1!"
}
# Function with return value
function add() {
echo $(($1 + $2))
}
Function Usage
greet "John" # Call function with argument
RESULT=$(add 5 3) # Capture function output
Input and Output
Command Line Arguments
# Access arguments
echo $1 # First argument
echo $2 # Second argument
echo $# # Number of arguments
echo $@ # All arguments
User Input
# Read user input
read -p "Enter your name: " NAME
read -s -p "Enter password: " PASSWORD
File Operations
File Testing
# Check if file exists
if [ -f "file.txt" ]; then
echo "File exists"
fi
# Check if directory exists
if [ -d "directory" ]; then
echo "Directory exists"
fi
File Reading
# Read file line by line
while read line; do
echo "$line"
done < "file.txt"
Error Handling
Exit Codes
# Check command success
if command; then
echo "Success"
else
echo "Failed"
fi
# Exit with status
exit 1 # Exit with error
Error Trapping
# Trap errors
set -e # Exit on error
trap 'echo "Error occurred"' ERR
Best Practices
-
Script Organization
- Use clear variable names
- Add comments
- Follow consistent formatting
- Use functions for modularity
-
Error Handling
- Check for errors
- Use proper exit codes
- Implement error messages
- Handle edge cases
-
Security
- Validate input
- Use quotes for variables
- Check file permissions
- Avoid command injection
Advanced Topics
Regular Expressions
# Pattern matching
if [[ $STRING =~ ^[0-9]+$ ]]; then
echo "Numeric string"
fi
Process Management
# Background processes
command &
# Wait for process
wait $PID
# Kill process
kill $PID
Next Steps
Continue learning about:
- Advanced shell features
- Script optimization
- Debugging techniques
- System administration scripts
- Automation tools