Bash First Script
Creating and running your first Bash script
📝 Your First Bash Script
A Bash script is a text file containing commands that execute sequentially. Create a file with .sh extension, add the shebang line, write commands, make it executable, and run it to automate tasks efficiently.
#!/bin/bash
echo "Hello, World!"
Output:
Hello, World!
Script Components
Shebang
First line specifying interpreter
#!/bin/bash
Comments
Documentation for your code
# This is a comment
Commands
Instructions to execute
echo "Hello"
Permissions
Make script executable
chmod +x script.sh
🔹 Creating Your First Script
To create a Bash script, save commands in a text file with a .sh extension and a shebang line. Start with #!/bin/bash to specify the interpreter. Make it executable with chmod +x script.sh and run it with ./script.sh. A simple first script might just echo "Hello, World!". This process turns a sequence of shell commands into an automated, reusable program. Always include comments to explain the script's purpose and use clear, consistent naming for files and variables to establish good habits from the start.
# Step 1: Create a new file
touch hello.sh
# Step 2: Open in text editor (nano, vim, or any editor)
nano hello.sh
# Step 3: Add this content:
#!/bin/bash
# My first Bash script
echo "Hello, World!"
echo "Today is $(date)"
# Step 4: Save and exit (Ctrl+X, then Y, then Enter in nano)
# Step 5: Make it executable
chmod +x hello.sh
# Step 6: Run the script
./hello.sh
Output:
Hello, World! Today is Wed Oct 8 14:30:22 UTC 2025
🔹 Understanding the Shebang
The shebang (#!/bin/bash) is the first line in executable scripts that tells the system which interpreter to use. This directive ensures your script runs with the correct shell environment and available features. While #!/bin/bash is common, you can specify other interpreters like #!/usr/bin/python3 for Python scripts or #!/bin/sh for POSIX-compliant shells. The shebang must be the absolute path to the interpreter and appear on the very first line without preceding spaces or comments for proper script execution.
#!/bin/bash
# Standard Bash shebang
#!/usr/bin/env bash
# Portable shebang (finds bash in PATH)
#!/bin/sh
# POSIX shell (more compatible)
# Example script with shebang
#!/bin/bash
echo "This script uses Bash"
echo "Bash version: $BASH_VERSION"
Output:
This script uses Bash Bash version: 5.1.16(1)-release
🔹 Script with Variables
Variables in Bash scripts store data that can be referenced and manipulated throughout your code. Create variables with variable_name="value" and access them with $variable_name. They can hold strings, numbers, file paths, or command outputs using command substitution ($(command)). Variables make scripts dynamic and reusable across different systems and scenarios. Proper naming conventions (uppercase for constants, lowercase for variables) and quoting practices prevent errors and make your scripts more maintainable and adaptable to changing requirements.
#!/bin/bash
# Script with variables
# Define variables
name="John"
age=25
city="New York"
# Use variables
echo "Name: $name"
echo "Age: $age"
echo "City: $city"
# Command substitution
current_date=$(date +%Y-%m-%d)
echo "Date: $current_date"
# Arithmetic
result=$((age + 5))
echo "In 5 years: $result"
Output:
Name: John Age: 25 City: New York Date: 2025-10-08 In 5 years: 30
🔹 Interactive Script
Interactive Bash scripts accept user input during execution to create dynamic, responsive programs. Use the read command to capture keyboard input into variables, optionally with the -p flag to display prompts. You can validate input, provide default values, and create menu-driven interfaces that guide users through complex operations. Interactive elements transform static scripts into flexible tools that adapt to user preferences, making them ideal for installation wizards, configuration tools, and educational applications that require user participation.
#!/bin/bash
# Interactive greeting script
echo "Welcome to the Greeting Script!"
echo "================================"
# Get user input
read -p "Enter your name: " username
read -p "Enter your age: " userage
# Display personalized message
echo ""
echo "Hello, $username!"
echo "You are $userage years old."
# Calculate birth year (approximate)
current_year=$(date +%Y)
birth_year=$((current_year - userage))
echo "You were born around $birth_year."
Output:
Welcome to the Greeting Script! ================================ Enter your name: Alice Enter your age: 28 Hello, Alice! You are 28 years old. You were born around 1997.
🔹 Script with Conditions
Conditional statements enable Bash scripts to make decisions and execute different code paths based on evaluations. The if-then-elif-else-fi structure tests conditions using test operators ([ ] or [[ ]]) and executes corresponding code blocks. Conditions can check file properties (-f for file exists), string comparisons (==), or numerical relationships (-gt for greater than). This logical branching creates intelligent scripts that adapt to system states, user input, file conditions, and environmental factors for robust automation.
#!/bin/bash
# Script with conditional logic
read -p "Enter a number: " number
# Check if number is positive, negative, or zero
if [ $number -gt 0 ]; then
echo "$number is positive"
elif [ $number -lt 0 ]; then
echo "$number is negative"
else
echo "$number is zero"
fi
# Check if number is even or odd
if [ $((number % 2)) -eq 0 ]; then
echo "$number is even"
else
echo "$number is odd"
fi
Output:
Enter a number: 42 42 is positive 42 is even
🔹 Running Scripts Different Ways
Bash scripts can be executed using multiple methods, each with specific use cases and requirements. Run with bash script.sh for debugging, ./script.sh after making executable with chmod +x, or source script.sh to run in the current shell. Adding scripts to directories in your PATH enables system-wide access. Each method affects variable scope, permission requirements, and current directory context. Understanding these differences helps you choose the appropriate execution method for development, production, or interactive use cases.
# Method 1: Direct execution (requires execute permission)
chmod +x script.sh
./script.sh
# Method 2: Using bash command (no execute permission needed)
bash script.sh
# Method 3: Using source or . (runs in current shell)
source script.sh
. script.sh
# Method 4: Specify full path
/home/user/scripts/script.sh
# Method 5: Add to PATH and run from anywhere
export PATH=$PATH:/home/user/scripts
script.sh
Execution Methods:
- ./script.sh - Most common, requires execute permission
- bash script.sh - No permission needed, creates new shell
- source script.sh - Runs in current shell, affects environment
- Full path - Run from anywhere without ./