Shell scripts automate repetitive tasks and combine commands into powerful workflows.
Basic Script Structure
#!/bin/bash
# This is a comment
echo "Hello, World!"
Make it executable: chmod +x script.sh
Variables
NAME="Linux"
echo "Welcome to $NAME"
echo "Current directory: $(pwd)"
Control Structures
Conditionals
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
Loops
# For loop
for file in *.txt; do
echo "Processing $file"
done
# While loop
while [ condition ]; do
commands
done
Functions
function greet() {
echo "Hello, $1"
}
greet "World"
Input and Arguments
# Read from user
read -p "Enter name: " name
# Command-line arguments
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"
Error Handling
set -e # Exit on error
set -u # Exit on undefined variable
set -o pipefail # Catch errors in pipes
Practical Example
#!/bin/bash
# Backup script
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d)
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p "$BACKUP_DIR"
fi
tar -czf "$BACKUP_DIR/backup-$DATE.tar.gz" /home/user
echo "Backup completed: backup-$DATE.tar.gz"
Shell scripting is the foundation of Linux automation. Start simple and build complexity gradually.