Bash Scripting Tutorial for Beginners
For system administrators, DevOps engineers, and backend developers working in Linux environments, automating repetitive tasks is essential for productivity and reliability. Whether deploying applications, managing system backups, parsing log files, or orchestrating server maintenance, the **Bourne Again SHell (Bash)** is the default command interpreter on most Linux distributions.
This comprehensive tutorial walks through the fundamentals of Bash scripting, covering shebangs, execution permissions, variables, conditional statements, loops, and practical automation scripts.
1. Writing and Executing Your First Bash Script
Every Bash script begins with a **shebang** (`#! /bin/bash`), which tells the operating system which interpreter should be used to parse the file.
#! /bin/bash
# hello.sh - Your first bash script
echo "Hello, World! Welcome to CodeCrown Linux Tutorials."
echo "Current logged-in user: $USER"
echo "Current working directory: $PWD"
# To make the script executable and run it via terminal:
chmod +x hello.sh
./hello.sh
2. Variables, Environment, and User Input
Variables in Bash store string and numeric values. You can assign values directly or capture user input dynamically using the `read` command.
#! /bin/bash
# Defining variables
SERVER_NAME="production-api-01"
# Accepting user input
echo -n "Enter your deployment environment (staging/production): "
read ENV_NAME
echo "Target Environment Selected: $ENV_NAME on server$SERVER_NAME"
3. Conditional Statements (`if-else`)
Bash conditional statements evaluate file attributes, strings, and numeric comparisons using square brackets `[ ... ]` or double brackets `[[ ... ]]`.
#! /bin/bash
CONFIG_FILE="/etc/nginx/nginx.conf"
if [ -f "$CONFIG_FILE" ]; then
echo "Configuration file $CONFIG_FILE exists."
else
echo "Error: Configuration file not found!"
exit 1
fi
4. Iteration with Loops (`for` and `while`)
Loops automate repetitive tasks across arrays, sequences, or file streams.
#! /bin/bash
# For loop iterating over a list of microservices
SERVICES=("auth-service" "payment-service" "notification-service")
echo "Starting deployment sequence..."
for service in "${SERVICES[@]}"; do
echo "-> Deploying $service..."
sleep 1
done
echo "All services deployed successfully!"
Conclusion
Mastering Bash scripting—from writing executable scripts and handling user input to evaluating conditionals and automating loops—empowers developers and system administrators to build powerful, efficient automation workflows in Linux.