Shell Scripting

"Simplify Bash Scripting : Beginner to Pro with 50 Essential Scripts" 🧑‍💻read

Here's a list of 50 common Bash scripts with explanations:

  1. Hello World: Prints "Hello, World!" to the terminal.

    Title: "Hello, Bash World: Your First Step into Scripting Brilliance"

    Script:ls

      #!/bin/bash
      echo "Hello, World!"
    

    Explanation: "This script serves as your initiation into the realm of Bash scripting brilliance. With a simple 'echo' command, it prints the timeless message 'Hello, World!' to the terminal, marking the beginning of your journey into the world of scripting mastery."

  2. Script Title: File Backup

      #!/bin/bash
      source_dir="/path/to/source"
      backup_dir="/path/to/backup"
      timestamp=$(date +%Y%m%d%H%M%S)
      backup_file="backup_$timestamp.tar.gz"
      tar -czvf "$backup_dir/$backup_file" "$source_dir"
    

    Explanation:
    This script creates a timestamped backup of a directory using tar compression. It specifies the source directory and backup directory paths, generates a timestamp, and creates a backup file with the timestamp appended to its name using tar compression.


    Script Title: Directory Listing

      #!/bin/bash
      ls -l
    

    Explanation:
    This script lists files and directories in the current directory with details, including permissions, ownership, size, and modification time.


    Script Title: File Count

      #!/bin/bash
      file_count=$(ls | wc -l)
      echo "Number of files: $file_count"
    

    Explanation:
    This script counts the number of files in the current directory using the ls command piped into wc -l, which counts the lines. It then echoes the count with an informative message.


    Script Title: Disk Usage

      #!/bin/bash
      df -h
    

    Explanation:
    This script displays disk usage information, including total, used, and available disk space, and usage percentage for all mounted filesystems.


    Script Title: System Info

      #!/bin/bash
      uname -a
    

    Explanation:
    This script prints system information, including the kernel version, hostname, architecture, and operating system.


    Script Title: File Rename

      #!/bin/bash
      old_name="old.txt"
      new_name="new.txt"
      mv "$old_name" "$new_name"
    

    Explanation:
    This script renames a file from "old.txt" to "new.txt" using the mv command.


    Script Title: File Permissions

      #!/bin/bash
      file="file.txt"
      chmod +x "$file"
    

    Explanation:
    This script grants execute permission to a file named "file.txt" using the chmod command.


    Script Title: User Info

      #!/bin/bash
      username=$(whoami)
      echo "Current user: $username"
    

    Explanation:
    This script retrieves the current user's username using the whoami command and echoes it with an informative message.


    Script Title: Process List

      #!/bin/bash
      ps aux
    

    Explanation:
    This script lists all running processes along with detailed information, including the process ID, CPU usage, memory usage, and command.


    Script Title: Process Kill

      #!/bin/bash
      process_id=12345
      kill -9 "$process_id"
    

    Explanation:
    This script kills a process by its process ID using the kill command with the -9 signal, which forces termination.


    Script Title: Check Internet Connection

      #!/bin/bash
      ping -c 5 google.com
    

    Explanation:
    This script checks internet connectivity by pinging Google five times and displaying the results.


    Script Title: Disk Cleanup

      #!/bin/bash
      du -sh /var/log/*
      rm -rf /var/log/*
    

    Explanation:
    This script displays disk usage of log files in the "/var/log" directory and then deletes them using the rm command with the -rf options.Conclusion: These scripts cover various tasks, from basic file operations to advanced tasks like JSON parsing and PDF conversion. Start with simpler scripts and gradually move to complex ones as you gain familiarity with Bash. 📝


    Script Title: System Shutdown

      #!/bin/bash
    
      # Shutdown the system immediately
      shutdown -h now
    

    Explanation: This script utilizes the shutdown command with the -h option to initiate an immediate system shutdown. The -h option specifies a halt action, causing the system to shut down completely. By using the now parameter, the shutdown process begins immediately without any delay. This script is useful for quickly shutting down the system when needed.


    Script Title: System Reboot

      #!/bin/bash
    
      # Reboot the system
      reboot
    

    Explanation: This script simply initiates a system reboot using the reboot command. When executed, the system will be restarted, causing all processes to terminate, and the operating system to reload, resulting in a full system reboot.


      #!/bin/bash
    
      # Define search directory and search term
      search_dir="/path/to/search"
      search_term="pattern"
    
      # Search for specified pattern recursively in files within the search directory
      grep -r "$search_term" "$search_dir"
    

    Explanation: This script facilitates file searching by utilizing the grep command with the -r option, which recursively searches for the specified pattern ($search_term) within files located in the designated search directory ($search_dir). This script is helpful for quickly locating files containing specific content or patterns within a directory structure.


    Script Title: Disk Space Alert

     #!/bin/bash
    
     #set disk space threshold (Percentage)
     threshold=95
    
     #Get current disk usage percentage for root filesystem
     current_usage=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
    
     #Check if current disk usage exceeds the threshold
     if [ "$current_usage" -ge "$threshold" ]; then
             echo "Disk space is running low!"
     else
             echo "Disk space is okay"
     fi
    

    Explanation: This script monitors disk space usage by retrieving the percentage of disk space used on the root filesystem (/). It compares this usage with a predefined threshold (threshold). If the current usage exceeds the threshold, an alert message indicating low disk space is displayed; otherwise, a message confirming sufficient disk space is printed.


    Script Title: Check Service Status

      #!/bin/bash
    
      # Specify the service name to check
      service_name="nginx"
    
      # Check if the service is active
      if systemctl is-active --quiet "$service_name"; then
          echo "$service_name is running."
      else
          echo "$service_name is not running."
      fi
    

    Explanation: This script checks the status of a specified system service (nginx in this case) using the systemctl is-active command. If the service is active, a message confirming that the service is running is displayed. Otherwise, a message indicating that the service is not running is printed. This script is useful for monitoring the status of critical system services.


    Script Title: System Backup Script

      #!/bin/bash
    
      # Define source and backup directories
      source_dir="/path/to/source"
      backup_dir="/path/to/backup"
    
      # Generate timestamp
      timestamp=$(date +%Y%m%d%H%M%S)
    
      # Define backup file name with timestamp
      backup_file="backup_$timestamp.tar.gz"
    
      # Create timestamped backup using tar compression
      tar -czvf "$backup_dir/$backup_file" "$source_dir"
    

    Explanation: This script automates the process of creating a timestamped backup of a directory specified by $source_dir. It generates a timestamp using the date command and constructs a backup file name incorporating this timestamp. The tar command is then used to compress and archive the contents of the source directory, creating the backup file in the specified backup directory ($backup_dir).


    Script Title: Log Rotation

      #!/bin/bash
    
      # Specify log file and maximum log size
      log_file="/path/to/logfile.log"
      max_log_size=10M
    
      # Check if log file exists
      if [ -f "$log_file" ]; then
          # Get current size of log file
          current_size=$(du -b "$log_file" | awk '{print $1}')
    
          # Check if current size exceeds maximum log size
          if [ "$current_size" -ge "$max_log_size" ]; then
              # Rotate log file by renaming it
              mv "$log_file" "$log_file.old"
    
              # Create a new empty log file
              touch "$log_file"
          fi
      fi
    

    Explanation: This script implements log rotation by checking the size of the specified log file ($log_file). If the log file exists and its size exceeds the maximum log size ($max_log_size), it renames the existing log file by appending ".old" to its name and creates a new empty log file in its place. This ensures that log files do not grow indefinitely and helps manage disk space usage.


    Script Title: User Management

      #!/bin/bash
    
      # Define username and password
      username="newuser"
      password="password123"
    
      # Create a new user
      useradd "$username"
    
      # Set password for the new user
      echo "$username:$password" | chpasswd
    

    Explanation: This script automates user management tasks by creating a new user ($username) and setting their password ($password). It uses the useradd command to create the user and the chpasswd command to set the password for the user. This script simplifies the process of user creation and password assignment.


    Script Title: File Encryption

      #!/bin/bash
    
      # Specify the file to encrypt
      file_to_encrypt="file.txt"
    
      # Encrypt the file using GPG
      gpg -c "$file_to_encrypt"
    

    Explanation: This script encrypts a specified file ($file_to_encrypt) using GPG (GNU Privacy Guard). The -c option is used with gpg to perform symmetric encryption, which requires a passphrase to encrypt and decrypt the file.


    Script Title: File Decryption

      #!/bin/bash
    
      # Specify the encrypted file
      encrypted_file="file.txt.gpg"
    
      # Decrypt the encrypted file and save as decrypted_file.txt
      gpg -d "$encrypted_file" > "decrypted_file.txt"
    

    Explanation: This script decrypts an encrypted file ($encrypted_file) using GPG. The -d option is used with gpg to decrypt the file. The decrypted content is then redirected (>) to a new file named decrypted_file.txt.


    Script Title: File Compression

      #!/bin/bash
    
      # Specify the compressed file
      compressed_file="compressed_file.tar.gz"
    
      # Decompress the file using tar and gzip
      tar -xzvf "$compressed_file"
    

    Explanation: This script decompresses a specified compressed file ($compressed_file) using the tar command with options -x (extract), -z (use gzip), and -v (verbose). The file is decompressed and its contents are extracted to the current directory.


    Script Title: File Decompression

      #!/bin/bash
    
      # Specify the compressed file
      compressed_file="compressed_file.tar.gz"
    
      # Decompress the file using tar and gzip
      tar -xzvf "$compressed_file"
    

    Explanation: This script decompresses a specified compressed file ($compressed_file) using the tar command with options -x (extract), -z (use gzip), and -v (verbose). The file is decompressed and its contents are extracted to the current directory.


    Script Title: CSV File Processing

      #!/bin/bash
    
      # Specify the input CSV file and output text file
      input_csv="data.csv"
      output_file="output.txt"
    
      # Extract specific columns from the CSV file and save them to a new file
      awk -F ',' '{print $1,$2}' "$input_csv" > "$output_file"
    

    Explanation: This script processes a CSV file ($input_csv) and extracts specific columns using awk command. The -F ',' option specifies that the fields are separated by commas. Columns 1 and 2 are extracted and saved to a new text file ($output_file).


    Script Title: Log Analysis

      #!/bin/bash
    
      # Specify the log file
      log_file="access.log"
    
      # Count unique IP addresses and total error occurrences
      unique_ips=$(awk '{print $1}' "$log_file" | sort -u | wc -l)
      error_count=$(grep -c 'ERROR' "$log_file")
    
      # Display analysis results
      echo "Unique IPs: $unique_ips"
      echo "Total Errors: $error_count"
    

    Explanation: This script analyzes an access log file ($log_file) to count unique IP addresses and occurrences of errors. It uses awk to extract IP addresses from the log file, sort -u to filter out duplicate IP addresses, and wc -l to count the number of unique IP addresses. It also uses grep -c to count the occurrences of 'ERROR' in the log file. Finally, it displays the analysis results.


    Script Title: Send Email Alert

      #!/bin/bash
    
      # Define email parameters
      email="user@example.com"
      subject="Alert"
      message="Disk space is running low!"
    
      # Send email alert
      echo "$message" | mail -s "$subject" "$email"
    

    Explanation: This script sends an email alert to a specified email address ($email) with a subject ($subject) and message ($message). It utilizes the mail command to send the email with the provided subject and message.


    Script Title: Database Backup

      #!/bin/bash
    
      # Define database name and backup file name
      db_name="mydb"
      backup_file="backup.sql"
    
      # Create MySQL database backup
      mysqldump -u username -p$password "$db_name" > "$backup_file"
    

    Explanation: This script creates a backup of a MySQL database ($db_name) using mysqldump command with specified username and password. The backup is then saved to a file named $backup_file.


    Script Title: SSH Key Generation

      #!/bin/bash
    
      # Generate an SSH key pair
      ssh-keygen -t rsa -b 4096 -f ~/.ssh/mykey
    

    Explanation: This script generates an SSH key pair using the ssh-keygen command with RSA encryption, 4096-bit key size, and the specified file path (~/.ssh/mykey).


    Script Title: SSH Key Copy

      #!/bin/bash
    
      # Copy SSH public key to a remote server for passwordless login
      ssh-copy-id user@hostname
    

    Explanation: This script copies the SSH public key to a remote server (user@hostname) using the ssh-copy-id command, enabling passwordless login to the remote server using the generated SSH key pair.


    Script Title: File Comparison

      #!/bin/bash
    
      # Define file paths
      file1="file1.txt"
      file2="file2.txt"
    
      # Compare two files and print result
      if cmp -s "$file1" "$file2"; then
          echo "Files are identical."
      else
          echo "Files are different."
      fi
    

    Explanation: This script compares two files ($file1 and $file2) using the cmp command. If the files are identical, it prints "Files are identical." Otherwise, it prints "Files are different."


    Script Title: Cron Job Example

      #!/bin/bash
    
      # Define backup directory and timestamp
      backup_dir="/path/to/backup"
      timestamp=$(date +%Y%m%d%H%M%S)
    
      # Create backup file with timestamp
      backup_file="backup_$timestamp.tar.gz"
    
      # Perform backup using tar
      tar -czvf "$backup_dir/$backup_file" /path/to/source
    

    Explanation: This script creates a timestamped backup file using tar command and compresses it using gzip. It is suitable for scheduling as a cron job to automate backups at regular intervals.


    Script Title: Folder Synchronization

      #!/bin/bash
    
      # Define source and destination directories
      source_dir="/path/to/source"
      destination_dir="/path/to/destination"
    
      # Synchronize contents of source directory to destination directory using rsync
      rsync -av "$source_dir/" "$destination_dir/"
    

    Explanation: This script synchronizes the contents of two directories ($source_dir and $destination_dir) using the rsync command with options -av (archive mode and verbose output), ensuring that the destination directory matches the source directory's contents.


    Script Title: URL Download

      #!/bin/bash
    
      # Define URL and output file name
      url="https://example.com/file.txt"
      output_file="downloaded_file.txt"
    
      # Download file from URL using wget
      wget "$url" -O "$output_file"
    

    Explanation: This script downloads a file from a specified URL ($url) using the wget command and saves it to a file with the specified output file name ($output_file).


    Script Title: Input Validation

      #!/bin/bash
    
      # Prompt user to enter a number
      read -p "Enter a number: " number
    
      # Validate input to ensure it is a number
      if [[ ! "$number" =~ ^[0-9]+$ ]]; then
          echo "Invalid input. Please enter a number."
      else
          echo "You entered: $number"
      fi
    

    Explanation: This script prompts the user to enter a number and validates the input using a regular expression. If the input is not a number (i.e., it does not consist entirely of digits), it displays an error message. Otherwise, it confirms the input.


    Script Title: String Manipulation

      #!/bin/bash
    
      # Define the input string
      string="Hello, World!"
    
      # Convert the string to uppercase
      uppercase_string=$(echo "$string" | tr '[:lower:]' '[:upper:]')
    
      # Print the uppercase string
      echo "$uppercase_string"
    

    Explanation: This script demonstrates how to manipulate strings in Bash by converting a given string to uppercase using the tr command.


    Script Title: File Watcher

      #!/bin/bash
    
      # Specify the directory to watch
      directory="/path/to/watch"
    
      # Watch the directory for file changes using inotifywait
      inotifywait -m -r -e create,modify,delete "$directory" |
      while read path action file; do
          echo "File $file was $action."
      done
    

    Explanation: This script utilizes inotifywait to monitor a specified directory for file creation, modification, or deletion events. It continuously listens for such events and prints a message indicating the action performed on the file.


    Script Title: JSON Parsing

      #!/bin/bash
    
      # Define the JSON string
      json_string='{"name": "John", "age": 30}'
    
      # Extract specific fields from the JSON string using jq
      name=$(echo "$json_string" | jq -r '.name')
      age=$(echo "$json_string" | jq -r '.age')
    
      # Print the extracted fields
      echo "Name: $name, Age: $age"
    

    Explanation: This script demonstrates parsing JSON data and extracting specific fields (name and age) using the jq command-line JSON processor.


    Script Title: Zip File Compression

      #!/bin/bash
    
      # Specify the file to compress
      file_to_compress="file.txt"
    
      # Compress the file using ZIP compression
      zip "compressed_file.zip" "$file_to_compress"
    

    Explanation: This script compresses a specified file using ZIP compression.


    Script Title: Zip File Extraction

      #!/bin/bash
    
      # Specify the ZIP file to extract
      zip_file="compressed_file.zip"
    
      # Extract files from the ZIP archive
      unzip "$zip_file"
    

    Explanation: This script extracts files from a specified ZIP archive.


    Script Title: PDF Conversion

      #!/bin/bash
    
      # Specify the input document and output PDF file
      input_file="document.docx"
      output_file="document.pdf"
    
      # Convert the document to PDF using LibreOffice
      libreoffice --headless --convert-to pdf "$input_file"
    

    Explanation: This script converts a document to PDF format using LibreOffice.


    Script Title: CSV to Excel

      #!/bin/bash
    
      # Specify the input CSV file and output Excel file
      input_csv="data.csv"
      output_xlsx="data.xlsx"
    
      # Convert the CSV file to an Excel (XLSX) file using ssconvert
      ssconvert "$input_csv" "$output_xlsx"
    

    Explanation: This script converts a CSV file to an Excel (XLSX) file using Gnumeric’s ssconvert.


    Script Title: File Splitting

      #!/bin/bash
    
      # Specify the input file to split
      input_file="large_file.txt"
    
      # Split the input file into smaller parts
      split -b 1M "$input_file" "split_file"
    

    Explanation: This script splits a large file into smaller parts of 1MB each using the split command.


    Script Title: File Joining

      #!/bin/bash
    
      # Concatenate split files to reconstruct the original file
      cat split_file* > "large_file.txt"
    

    Explanation: This script joins split files (with names starting with "split_file") to reconstruct the original file. It uses the cat command to concatenate the contents of split files into a single file named "large_file.txt".


    Script Title: IP Address Validation

      #!/bin/bash
    
      # Prompt user to enter an IP address
      read -p "Enter an IP address: " ip_address
    
      # Validate input as an IP address
      if [[ $ip_address =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
          echo "Valid IP address: $ip_address"
      else
          echo "Invalid IP address."
      fi
    

    Explanation: This script validates user input as an IP address using a regular expression. It prompts the user to enter an IP address and checks if the input matches the pattern of four numbers separated by periods.


    Script Title: URL Validation

      #!/bin/bash
    
      # Prompt user to enter a URL
      read -p "Enter a URL: " url
    
      # Validate input as a URL
      if [[ $url =~ ^(http|https)://[A-Za-z0-9.-/]+$ ]]; then
          echo "Valid URL: $url"
      else
          echo "Invalid URL."
      fi
    

    Explanation: This script validates user input as a URL using a regular expression. It prompts the user to enter a URL and checks if the input matches the pattern of a URL starting with "http://" or "https://" followed by alphanumeric characters, periods, hyphens, and slashes.


    Script Title: File Permissions Report

      #!/bin/bash
    
      # Generate a report of file permissions for all files in a directory
      find /path/to/files -type f -exec ls -l {} \; > permissions_report.txt
    

    Explanation: This script creates a report of file permissions for all files in a specified directory (/path/to/files). It uses the find command to locate files, -type f to filter regular files, -exec ls -l {} \; to list detailed permissions for each file, and redirects the output to a file named "permissions_report.txt".


    Script Title: Password Generator

      #!/bin/bash
    
      # Specify password length and characters to use
      length=12
      characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()"
    
      # Generate a random password
      password=$(head /dev/urandom | tr -dc "$characters" | head -c "$length")
    
      # Print the generated password
      echo "Generated Password: $password"
    

    Explanation: This script generates a random password of specified length ($length) using characters from a predefined set ($characters). It reads random data from /dev/urandom, filters characters using tr -dc, and selects the specified length using head -c. Finally, it prints the generated password.