Shell Scripting Basics
A shell script is an automation tool that bundles multiple commands into a single file for execution.
1. Getting Started with Shell Scripts
On the first line of your file, include a Shebang to specify that the file is a shell script.
#!/bin/bash
echo "Hello, Linux!"
How to run:
chmod +x hello.sh # Grant execution permission
./hello.sh # Run from the current directory
2. Defining and Using Variables
- Ensure there are no spaces around the
=sign during declaration. - Use the
$symbol when referencing the variable.
NAME="Linux"
echo "Welcome to $NAME"
3. Conditional Statements (if)
Conditions are written inside square brackets [ ]. Pay close attention to the spaces within the brackets.
FILE="data.log"
if [ -f "$FILE" ]; then
echo "The file exists."
else
echo "The file does not exist."
fi
4. Loops (for / while)
# Iterating from 1 to 5
for i in {1..5}; do
echo "Number: $i"
done
5. Practical Example: Backup Script
#!/bin/bash
DATE=$(date +%Y%m%d)
BACKUP_DIR="/backup/$DATE"
mkdir -p $BACKUP_DIR
cp -r /var/www/html $BACKUP_DIR
echo "Backup complete: $BACKUP_DIR"
Mastering shell scripting allows you to automate a large portion of server operations. Great job!