Background
HOME / IT / BASH-101

Bash 101: Introduction to Linux Shell Scripting

A beginner's guide to Bash shell scripting, covering basic commands, scripting fundamentals, and automation on Linux systems

rnrran's profile picture
rnrran
Jan 28, 202520 min read
rnrran's avatar

Written by

rnrran

Feature added soon

Bash 101: Introduction to Linux Shell Scripting

Introduction

Bash (Bourne Again Shell) is the default shell on most Linux distributions and macOS. It's a command-line interpreter and scripting language that allows you to interact with your operating system and automate tasks.

This guide will introduce you to Bash fundamentals, covering basic commands, shell scripting, and practical examples to get you started with Linux automation.

Bash Shell

What is Bash?

Bash is:

  • A Command-Line Shell: Interactive interface to the operating system
  • A Scripting Language: Write scripts to automate tasks
  • Unix-Compatible: Works on Linux, macOS, and Windows (WSL, Git Bash)
  • Text-Based: Works with text streams and files

Bash Versions

# Check Bash version
bash --version

# Most systems use Bash 4.x or 5.x
# macOS may have older version (3.2) due to licensing

Getting Started

Opening a Terminal

Linux:

  • Press Ctrl + Alt + T (most distributions)
  • Search for "Terminal" in applications
  • Right-click desktop → Open Terminal

macOS:

  • Open Terminal.app from Applications/Utilities
  • Use Spotlight: Cmd + Space, type "Terminal"

Windows:

  • Use WSL (Windows Subsystem for Linux)
  • Use Git Bash
  • Use PowerShell with Linux commands

Basic Navigation

# Print working directory
pwd

# List files and directories
ls
ls -l          # Long format
ls -a          # Show hidden files
ls -lh         # Human-readable sizes
ls -la         # Long format with hidden files

# Change directory
cd /home/user
cd ..          # Parent directory
cd ~           # Home directory
cd -           # Previous directory

# Create directory
mkdir mydir
mkdir -p dir1/dir2/dir3    # Create nested directories

# Remove directory
rmdir mydir                 # Empty directory only
rm -r mydir                 # Remove directory and contents
rm -rf mydir                # Force remove (be careful!)

Essential Commands

File Operations

# Create file
touch file.txt
echo "Hello" > file.txt
cat > file.txt << EOF
Line 1
Line 2
EOF

# View file content
cat file.txt
less file.txt              # Pager view
head file.txt              # First 10 lines
head -n 20 file.txt        # First 20 lines
tail file.txt              # Last 10 lines
tail -f file.txt           # Follow file (log monitoring)

# Copy file
cp source.txt dest.txt
cp -r sourcedir destdir     # Copy directory

# Move/rename file
mv old.txt new.txt
mv file.txt /path/to/dest/

# Delete file
rm file.txt
rm -i file.txt             # Interactive (ask before delete)

# Find files
find . -name "*.txt"
find /home -type f -name "*.log"
find . -size +100M         # Files larger than 100MB

Text Processing

# Search in files
grep "pattern" file.txt
grep -r "pattern" /path    # Recursive search
grep -i "pattern" file.txt # Case-insensitive
grep -v "pattern" file.txt # Invert match

# Count lines, words, characters
wc file.txt                # Lines, words, characters
wc -l file.txt             # Line count only

# Sort
sort file.txt
sort -r file.txt           # Reverse sort
sort -n file.txt           # Numeric sort

# Unique lines
sort file.txt | uniq
sort file.txt | uniq -c    # Count occurrences

# Cut columns
cut -d',' -f1,3 file.csv   # Comma-delimited, fields 1 and 3
cut -d':' -f1 /etc/passwd  # First field (usernames)

# Replace text
sed 's/old/new/g' file.txt
sed -i 's/old/new/g' file.txt  # In-place edit

# Advanced text processing
awk '{print $1}' file.txt  # Print first column
awk -F',' '{print $2}' file.csv  # Comma-delimited

System Information

# System information
uname -a                   # System information
hostname                   # Hostname
whoami                     # Current user
id                         # User and group IDs

# Process management
ps                         # Running processes
ps aux                     # All processes
top                        # Interactive process viewer
htop                       # Enhanced top (if installed)
kill PID                   # Kill process
killall processname        # Kill all processes by name

# System resources
df -h                      # Disk space
du -h                      # Directory size
free -h                    # Memory usage
uptime                     # System uptime

# Network
ifconfig                   # Network interfaces (may need: ip addr)
ip addr                    # Network interfaces
ping google.com
netstat -tulpn             # Network connections
ss -tulpn                  # Modern netstat alternative

Variables and Environment

Variables

# Set variable
name="John"
number=42

# Use variable
echo $name
echo "Hello, $name"
echo "Hello, ${name}!"

# Read-only variable
readonly PI=3.14

# Unset variable
unset name

Environment Variables

# View environment variables
env
printenv

# Common environment variables
echo $HOME
echo $USER
echo $PATH
echo $SHELL
echo $PWD

# Set environment variable
export MY_VAR="value"
export PATH=$PATH:/new/path

# Add to PATH permanently
echo 'export PATH=$PATH:/new/path' >> ~/.bashrc
source ~/.bashrc

Special Variables

$0          # Script name
$1, $2, ... # Command-line arguments
$#          # Number of arguments
$@          # All arguments
$*          # All arguments (as single string)
$?          # Exit status of last command
$$          # Process ID
$!          # Process ID of last background command

Input and Output

Output (Print)

# Print to stdout
echo "Hello, World!"
echo -e "Line 1\nLine 2"    # Enable escape sequences
echo -n "No newline"        # No trailing newline

# Printf (formatted output)
printf "Name: %s, Age: %d\n" "John" 30
printf "%.2f\n" 3.14159     # Floating point with 2 decimals

# Redirect output
echo "Hello" > file.txt     # Overwrite
echo "World" >> file.txt    # Append

Input

# Read from user
read name
echo "Hello, $name"

# Read with prompt
read -p "Enter your name: " name

# Read password (hidden)
read -s password

# Read multiple values
read first last
echo "First: $first, Last: $last"

# Read from file
while read line; do
    echo "$line"
done < file.txt

Control Structures

If-Else

# Basic if
if [ condition ]; then
    commands
fi

# If-else
if [ condition ]; then
    commands
else
    commands
fi

# If-elif-else
if [ condition1 ]; then
    commands
elif [ condition2 ]; then
    commands
else
    commands
fi

# Examples
if [ $number -gt 10 ]; then
    echo "Number is greater than 10"
fi

if [ -f "file.txt" ]; then
    echo "File exists"
else
    echo "File does not exist"
fi

Test Conditions

# File tests
[ -f file ]         # File exists and is regular file
[ -d dir ]          # Directory exists
[ -e path ]         # File/directory exists
[ -r file ]         # File is readable
[ -w file ]         # File is writable
[ -x file ]         # File is executable
[ -s file ]         # File is not empty

# String tests
[ -z string ]       # String is empty
[ -n string ]       # String is not empty
[ str1 = str2 ]     # Strings are equal
[ str1 != str2 ]    # Strings are not equal

# Numeric tests
[ num1 -eq num2 ]   # Equal
[ num1 -ne num2 ]   # Not equal
[ num1 -gt num2 ]   # Greater than
[ num1 -ge num2 ]   # Greater than or equal
[ num1 -lt num2 ]   # Less than
[ num1 -le num2 ]   # Less than or equal

# Logical operators
[ condition1 ] && [ condition2 ]  # AND
[ condition1 ] || [ condition2 ]  # OR
[ ! condition ]                    # NOT

Loops

# For loop
for i in 1 2 3 4 5; do
    echo $i
done

for file in *.txt; do
    echo "Processing $file"
done

# C-style for loop
for ((i=1; i<=10; i++)); do
    echo $i
done

# While loop
counter=0
while [ $counter -lt 5 ]; do
    echo "Counter: $counter"
    ((counter++))
done

# Until loop
counter=0
until [ $counter -ge 5 ]; do
    echo "Counter: $counter"
    ((counter++))
done

# Loop through file lines
while IFS= read -r line; do
    echo "$line"
done < file.txt

Case Statement

case $variable in
    pattern1)
        commands
        ;;
    pattern2)
        commands
        ;;
    *)
        default commands
        ;;
esac

# Example
case $day in
    Monday|Tuesday|Wednesday|Thursday|Friday)
        echo "Work day"
        ;;
    Saturday|Sunday)
        echo "Weekend"
        ;;
    *)
        echo "Invalid day"
        ;;
esac

Functions

# Define function
function greet() {
    echo "Hello, $1!"
}

# Call function
greet "John"

# Function with return value
function add() {
    local sum=$(($1 + $2))
    return $sum
}

add 5 3
result=$?
echo "Sum: $result"

# Function with output
function multiply() {
    echo $(($1 * $2))
}

result=$(multiply 5 3)
echo "Product: $result"

Bash Scripting

Creating Scripts

# Create script file
#!/bin/bash
# This is a comment

echo "Hello from script!"

# Make executable
chmod +x script.sh

# Run script
./script.sh

Script Structure

#!/bin/bash
# Script: hello.sh
# Description: Simple greeting script

# Variables
name="World"

# Functions
greet() {
    echo "Hello, $1!"
}

# Main script
greet "$name"

Command-Line Arguments

#!/bin/bash
# script.sh arg1 arg2 arg3

echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
echo "Number of arguments: $#"

Redirection and Pipes

Redirection

# Output redirection
command > file.txt        # Overwrite
command >> file.txt       # Append
command 2> error.log      # Redirect stderr
command > output.log 2>&1 # Redirect both stdout and stderr
command &> file.log       # Redirect both (bash 4+)

# Input redirection
command < file.txt
command << EOF
input lines
EOF

# Here document
cat << EOF
Line 1
Line 2
EOF

Pipes

# Pipe output to next command
ls -l | grep ".txt"
ps aux | grep "chrome"
cat file.txt | sort | uniq

# Multiple pipes
cat log.txt | grep "ERROR" | sort | uniq -c

Practical Examples

Example 1: System Backup Script

#!/bin/bash
# backup.sh - Simple backup script

BACKUP_DIR="/backup"
SOURCE_DIR="/home/user"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="backup_$DATE.tar.gz"

echo "Starting backup..."
tar -czf "$BACKUP_DIR/$BACKUP_FILE" "$SOURCE_DIR"

if [ $? -eq 0 ]; then
    echo "Backup completed: $BACKUP_FILE"
else
    echo "Backup failed!"
    exit 1
fi

Example 2: Log Monitoring

#!/bin/bash
# monitor.sh - Monitor log file for errors

LOG_FILE="/var/log/app.log"
KEYWORD="ERROR"

echo "Monitoring $LOG_FILE for '$KEYWORD'..."
tail -f "$LOG_FILE" | while read line; do
    if echo "$line" | grep -q "$KEYWORD"; then
        echo "[ALERT] $line"
    fi
done

Example 3: File Organizer

#!/bin/bash
# organize.sh - Organize files by extension

TARGET_DIR="$1"

if [ ! -d "$TARGET_DIR" ]; then
    echo "Directory not found!"
    exit 1
fi

for file in "$TARGET_DIR"/*; do
    if [ -f "$file" ]; then
        ext="${file##*.}"
        mkdir -p "$TARGET_DIR/$ext"
        mv "$file" "$TARGET_DIR/$ext/"
        echo "Moved $file to $ext/"
    fi
done

Best Practices

  1. Use Shebang: Always start scripts with #!/bin/bash
  2. Quote Variables: Use "$variable" to handle spaces
  3. Check Errors: Use set -e to exit on error
  4. Use Functions: Organize code into reusable functions
  5. Add Comments: Document your code
  6. Validate Input: Check arguments and files exist
  7. Use Meaningful Names: Clear variable and function names
  8. Handle Errors: Check exit codes and handle failures
  9. Test Scripts: Test in safe environment first
  10. Follow Conventions: Use consistent style

Conclusion

Bash is a powerful tool for Linux system administration and automation. This guide covered:

  • Basic Bash commands and navigation
  • Variables and environment
  • Input/output operations
  • Control structures and loops
  • Functions and scripting
  • Practical examples

Continue learning by:

  • Practicing daily tasks
  • Reading existing scripts
  • Building your own automation
  • Exploring advanced features
  • Joining Linux communities

Mastery of Bash will significantly improve your productivity on Linux systems.