Skip to content

Instantly share code, notes, and snippets.

@bglopez
Forked from devinci-it/README.md
Created February 7, 2026 16:56
Show Gist options
  • Select an option

  • Save bglopez/24af79ca07ddde4079168082dde13b0d to your computer and use it in GitHub Desktop.

Select an option

Save bglopez/24af79ca07ddde4079168082dde13b0d to your computer and use it in GitHub Desktop.
This repository contains a collection of utility bash scripts for various tasks.

Utility Bash Scripts

This repository contains a collection of utility bash scripts for various tasks.

Usage

To use any of the scripts in this repository:

  1. Clone the repository or download the desired script.
  2. Make the script executable using the chmod +x command.
  3. Execute the script from the command line.

Example:

chmod +x script_name.sh
./script_name.sh

Setup Script

The _setup.sh script automates the setup process for adding scripts with the .sh extension in the current directory (excluding those starting with _) to the .local/bin directory, removing the .sh extension, and making them executable. It also ensures that the script is run with sudo.

Usage

  1. Ensure that the script is run with sudo:

    sudo ./_setup.sh
  2. Follow the prompts to proceed with setting up the scripts.

  3. After completion, you can run the scripts without the .sh extension from anywhere in the command line.

Instructions

To enable calling each script using their respective aliases, append the following line to your shell configuration file:

  • For Bash (typically ~/.bashrc):

    source ~/.local/bin/_alias
  • For Zsh (typically ~/.zshrc):

    source ~/.local/bin/_alias

After appending the line, reload your shell configuration by running source ~/.bashrc (for Bash) or source ~/.zshrc (for Zsh).

#!/bin/bash
################################################################################
# Script Name: _alias.sh
# Description: This script defines aliases for other scripts located in the same
# directory, making them easily accessible.
# Aliases are only available within the current shell session.
# Usage: source _alias.sh
#
# To make aliases persistent and available in every new shell session:
# 1. Place this script in the same directory as the scripts you want to alias.
# 2. Add the following line to your shell's profile or rc file:
# source /path/to/_alias.sh
# Replace /path/to/_alias.sh with the actual path to this script.
# 3. Once added, the aliases will be automatically loaded in every new shell session.
################################################################################
# Define aliases for port-stop.sh script
alias killport='./port-stop.sh'
# Define aliases for path_manager.sh script
alias pathify='./path_manager.sh'
alias archie='./auto_archive.sh'
alias semver='./semver_util.sh'
# Usage instructions
echo "Aliases defined:"
echo "killport : Alias for './port-stop.sh'"
echo "pathify : Alias for './path_manager.sh'"
echo "archie : Alias for './auto_archive.sh'"
echo "To use the aliases, run 'source alias.sh' or '. alias.sh'."
#!/bin/bash
################################################################################
# Script Name: _setup.sh
# Description: This script automates the setup process for adding scripts with
# the .sh extension in the current directory (excluding those
# starting with '_') to the .local/bin directory, removing the .sh
# extension, and making them executable. It also ensures that the
# script is run with sudo.
################################################################################
# Check if the script is run with sudo
if [ "$(id -u)" != "0" ]; then
echo "This script must be run with sudo. Please use 'sudo ./_setup.sh'."
exit 1
fi
# List .sh files in the current directory (excluding those starting with '_')
sh_files=$(find . -maxdepth 1 -type f -name "*.sh" | grep -v "/_.*\.sh$")
# Check if there are .sh files to process
if [ -z "$sh_files" ]; then
echo "No .sh files found in the current directory (excluding those starting with '_')."
exit 1
fi
# Display summary of scanned scripts
echo "Summary of Scanned Scripts:"
echo "$sh_files" | sed 's|^\./||'
# Prompt before proceeding
read -p "Do you want to proceed with setting up these scripts? (y/n): " choice
case "$choice" in
[Yy]* ) ;;
* ) echo "Aborted."; exit 1;;
esac
# Destination directory
destination_dir="$HOME/.local/bin"
# Create the destination directory if it doesn't exist
mkdir -p "$destination_dir"
# Loop through each .sh file
for file in $sh_files; do
# Extract script name without the .sh extension
script_name=$(basename "$file" .sh)
# Copy the script to the destination directory
cp "$file" "$destination_dir/"
# Remove the .sh extension
mv "$destination_dir/$(basename "$file")" "$destination_dir/$script_name"
# Make the script executable
chmod +x "$destination_dir/$script_name"
echo "Script '$script_name' setup complete."
done
# Display stats
echo "Setup complete for $(echo "$sh_files" | wc -l) script(s)."
echo "You can now run the script(s) without the .sh extension from anywhere in the command line."
# Instructions for appending _alias script to shell configuration file
echo ""
echo "To enable calling each script using their respective aliases, append the following line to your shell configuration file:"
echo ""
echo "For Bash (typically ~/.bashrc):"
echo " source ~/.local/bin/_alias.sh"
echo ""
echo "For Zsh (typically ~/.zshrc):"
echo " source ~/.local/bin/_alias.sh"
echo ""
echo "After appending the line, reload your shell configuration by running 'source ~/.bashrc' (for Bash) or 'source ~/.zshrc' (for Zsh)."
#!/bin/bash
################################################################################
# Description: Directory Archiver Script
# This script archives directories within a specified source path,
# excluding the 'latest' symbolic link,
# and stores the archives in a destination directory.
# It prompts the user for confirmation before proceeding with the archiving process.
################################################################################
# Author: devinci-it
# Date: 2024
# Function to check if running with sudo
check_sudo() {
if [ "$EUID" -ne 0 ]; then
echo "Please run this script with sudo."
exit 1
fi
}
# Function to prompt for source path
prompt_source_path() {
if [ -z "$1" ]; then
read -p "Enter source path: " source_path
else
source_path="$1"
fi
}
# Function to prompt for destination path
prompt_destination_path() {
if [ -z "$2" ]; then
read -p "Enter destination path: " destination_path
else
destination_path="$2"
fi
}
# Function to confirm the archiving task
confirm_task() {
echo "Source path: $source_path"
echo "Directories to be processed:"
for dir in "$source_path"/*; do
if [[ -d "$dir" && "$(basename "$dir")" != "latest" ]]; then
dir_name=$(basename "$dir")
echo "$dir_name"
fi
done
read -p "Do you want to proceed? (yes/no): " answer
if [[ "$answer" != "yes" ]]; then
echo "Exiting without processing directories."
exit 1
fi
}
# Function to create tar.gz file for a directory
create_archive() {
local dir_name="$1"
tar -czvf "$destination_path/${dir_name}.tar.gz" -C "$source_path" "$dir_name"
}
# Function to verify tar.gz file
verify_archive() {
local dir_name="$1"
if tar -tzvf "$destination_path/${dir_name}.tar.gz"; then
return 0 # No error occurred during verification
else
return 1 # Error occurred during verification
fi
}
# Function to remove processed directory
remove_directory() {
local dir="$1"
rm -rf "$dir"
}
# Main function
main() {
check_sudo
prompt_source_path "$1"
prompt_destination_path "$2"
confirm_task
# Loop over each directory in the source path
for dir in "$source_path"/*; do
if [[ -d "$dir" && "$(basename "$dir")" != "latest" ]]; then
dir_name=$(basename "$dir")
create_archive "$dir_name"
if verify_archive "$dir_name"; then
remove_directory "$dir"
else
read -p "Error occurred during verification. Do you want to proceed anyway? (yes/no): " answer
if [[ "$answer" != "yes" ]]; then
echo "Exiting without deleting files."
exit 1
else
remove_directory "$dir"
fi
fi
fi
done
}
# Call the main function
main "$@"
#!/bin/bash
##########################################################
# System Backup Script
#
# This script performs a backup of essential system files
# including /srv, /home, and /etc directories using rsync.
# The backups are stored in the specified directory.
# Progress of the backup is displayed during execution.
#
# Author: devinci-it
# Date: 2024
##########################################################
# Set variables
BACKUP_DIR="/mnt/HOMELAB-BACKUP-AGGREGATOR/SYSTEM_BACKUP_ESSENTIALS" # Specify the directory to store backups
ARCHIVE_DIR="/mnt/HOMELAB-BACKUP-AGGREGATOR/SYSTEM_BACKUP_ESSENTIALS_ARCHIVE" # Specify the directory to archive backups
TODAY=$(date +"%Y-%m-%d") # Get current date for backup folder name
YESTERDAY=$(date -d "yesterday" +"%Y-%m-%d") # Get previous day's date
LOG_FILE="/var/log/backup/backup_$TODAY.log" # Log file to store backup process logs
# Ensure log directory exists
ensure_log_directory() {
sudo mkdir -p /var/log/backup
}
# Function to log errors and exit script
log_error() {
local message="$1"
echo "$(date +"%Y-%m-%d %H:%M:%S") - Error: $message" | sudo tee -a "$LOG_FILE" > /dev/null
echo "$(date +"%Y-%m-%d %H:%M:%S") - Backup process failed" | sudo tee -a "$LOG_FILE" > /dev/null
cleanup
exit 1
}
# Function to perform cleanup
cleanup() {
echo "$(date +"%Y-%m-%d %H:%M:%S") - Performing cleanup" | sudo tee -a "$LOG_FILE" > /dev/null
sudo rm -rf "$BACKUP_DIR/$TODAY"
sudo rm -f "$BACKUP_DIR/latest"
}
# Perform backup of essential directories
perform_backup() {
sudo rsync -av --progress --exclude={/vendor/**,/env/**,/venv/**,.venv/**} /srv "$BACKUP_DIR/$TODAY" || log_error "Failed to backup /srv directory: Permission denied"
sudo rsync -av --progress --exclude={/vendor/**,/env/**,/venv/**,.venv/**} /home "$BACKUP_DIR/$TODAY" || log_error "Failed to backup /home directory: Permission denied"
sudo rsync -av --progress --exclude={/vendor/**,/env/**,/venv/**,.venv/**} /etc "$BACKUP_DIR/$TODAY" || log_error "Failed to backup /etc directory: Permission denied"
}
# Update latest link
update_latest_link() {
sudo ln -s "$TODAY" "$BACKUP_DIR/latest" || log_error "Failed to update latest link: Permission denied"
}
# Archive the previous day's backup
archive_previous_backup() {
sudo mkdir -p "$ARCHIVE_DIR"
sudo mv "$BACKUP_DIR/$YESTERDAY" "$ARCHIVE_DIR/$YESTERDAY"
}
# Update the MOTD file with notification message
update_motd() {
sudo bash -c 'cat > /etc/motd' <<'EOF'
============================================================
IMPORTANT NOTICE: CHECK YOUR BACKUP STATUS
============================================================
Dear User,
Please be informed that the backup process may have run recently.
Please check the backup status to ensure that all your data is safe.
Thank you,
Your System Administrator
EOF
}
# Main function to centralize execution
main() {
ensure_log_directory
echo "$(date +"%Y-%m-%d %H:%M:%S") - Backup process started" | sudo tee -a "$LOG_FILE" > /dev/null
if sudo mkdir -p "$BACKUP_DIR/$TODAY"; then
perform_backup
update_latest_link
archive_previous_backup
echo "$(date +"%Y-%m-%d %H:%M:%S") - Backup process completed successfully" | sudo tee -a "$LOG_FILE" > /dev/null
else
update_motd
echo "$(date +"%Y-%m-%d %H:%M:%S") - Backup directory doesn't exist. Notification banner displayed in /etc/motd" | sudo tee -a "$LOG_FILE" > /dev/null
fi
}
# Execute main function
main
#!/bin/bash
################################################################################
# Script Name: cleanup.sh
# Description: Script to clean caches and temporary files in Ubuntu.
# Usage: ./cleanup.sh
#
# This script performs the following tasks:
# - Cleans the package cache.
# - Clears the APT cache.
# - Removes old files from temporary directories.
# - Cleans up user-specific temporary files.
# - Rotates and clears systemd journal logs.
# - Clears browser cache (if applicable).
#
# To make aliases persistent and available in every new shell session:
# 1. Place this script in the same directory as the scripts you want to alias.
# 2. Add the following line to your shell's profile or rc file:
# source /path/to/cleanup.sh
# Replace /path/to/cleanup.sh with the actual path to this script.
# 3. Once added, the script can be executed using the command `cleanup.sh`.
################################################################################
# Function to clear the package cache
clean_package_cache() {
echo "Cleaning package cache..."
sudo apt clean
echo "Package cache cleaned."
}
# Function to clear the APT cache
clean_apt_cache() {
echo "Cleaning APT cache..."
sudo apt autoclean
echo "APT cache cleaned."
}
# Function to clear temporary files
clean_temp_files() {
echo "Cleaning temporary files..."
sudo apt install -y tmpreaper
sudo tmpreaper -a 1d /tmp
sudo tmpreaper -a 1d /var/tmp
echo "Temporary files cleaned."
}
# Function to clear user-specific temporary files
clean_user_temp_files() {
echo "Cleaning user-specific temporary files..."
rm -rf ~/.cache/*
echo "User-specific temporary files cleaned."
}
# Function to clear systemd journal logs
clean_systemd_logs() {
echo "Cleaning systemd journal logs..."
sudo journalctl --rotate
sudo journalctl --vacuum-size=100M
echo "Systemd journal logs cleaned."
}
# Function to clear browser cache (if applicable)
clean_browser_cache() {
echo "Cleaning browser cache..."
# Add commands to clear browser cache here
echo "Browser cache cleaned."
}
# Main function
main() {
clean_package_cache
clean_apt_cache
clean_temp_files
clean_user_temp_files
clean_systemd_logs
clean_browser_cache
echo "Cleanup completed."
}
# Run main function
main
#!/bin/bash
################################################################################
# Script Name: path_manager.sh
# Description: This script allows users to add a specified path to their PATH
# environment variable temporarily or persistently by appending
# it to their .bashrc or .zshrc file. It also includes a function
# to verify and rearrange PATH variables, removing duplicates and
# sorting them alphabetically.
#
# Usage: path_manager.sh <path_to_add>
# Arguments:
# <path_to_add> The path to be added to the PATH variable.
#
# Example:
# ./path_manager.sh /usr/local/bin
# This command adds the path '/usr/local/bin' to the PATH variable temporarily.
#
# Author: devinci-it
# Date: 2024
# Version: 1.0
################################################################################
# Function to add path to PATH temporarily
add_temporary_path() {
export PATH="$PATH:$1"
echo "Path '$1' added to PATH temporarily."
}
# Function to add path to user's .bashrc or .zshrc
add_persistent_path() {
if [ -f "$1" ]; then
if ! grep -q "export PATH=.*$2.*" "$1"; then
echo "export PATH=\$PATH:$2" >> "$1"
echo "Path '$2' added to $1."
else
echo "Path '$2' already exists in $1."
fi
else
echo "$1 not found. Please create the file manually."
fi
}
# Function to verify and rearrange PATH variables
verify_and_rearrange_path() {
# Split PATH variable into an array
IFS=":" read -ra path_array <<< "$PATH"
# Remove duplicates
unique_path=$(printf "%s\n" "${path_array[@]}" | awk '!seen[$0]++' | paste -sd ":" -)
# Rearrange PATH variables alphabetically
sorted_path=$(printf "%s\n" "${unique_path}" | tr ':' '\n' | sort | paste -sd ":" -)
# Update PATH variable
export PATH="$sorted_path"
echo "Path variables verified and rearranged."
}
# Main script
if [ $# -lt 1 ]; then
echo "Usage: $0 <path_to_add>"
exit 1
fi
path_to_add="$1"
# Add path temporarily
add_temporary_path "$path_to_add"
# Add path to user's .bashrc or .zshrc
while true; do
read -p "Do you want to add the path to your .bashrc or .zshrc? (y/n): " yn
case $yn in
[Yy]* ) add_persistent_path "$HOME/.bashrc" "$path_to_add"; add_persistent_path "$HOME/.zshrc" "$path_to_add"; break;;
[Nn]* ) break;;
* ) echo "Please answer yes or no.";;
esac
done
# Verify and rearrange PATH variables
verify_and_rearrange_path
#!/bin/bash
################################################################################
# Script Name: port_stop.sh
# Description: This script stops the process or service running on a specified
# port by sending a kill signal to the process ID (PID) associated
# with that port.
#
# Usage: ./port_stop.sh <port_number>
# Arguments:
# <port_number> The port number on which the process is running.
#
# Example:
# ./port_stop.sh 5173
# This command stops the process using port 5173.
#
# Author: devinci-it
# Date: 2024
# Version: 1.0
################################################################################
port=$1
# Check if port number is provided
if [ -z "$port" ]; then
echo "Please provide a port number."
exit 1
fi
# Find the process using the specified port
pid=$(sudo lsof -ti:$port)
# Check if process is running on the specified port
if [ -z "$pid" ]; then
echo "No process is using port $port."
else
# Stop the process
sudo kill $pid
echo "Process using port $port (PID: $pid) has been stopped."
fi
#!/bin/bash
################################################################################
# Script: semver_util.sh
#
# Description:
# This script fetches the latest Git tag, increments the major, minor, or patch
# version component, or creates a custom version tag. It optionally pushes the
# created tag to the remote origin.
#
# Usage:
# ./update_version.sh [--remote] <major|minor|patch|--custom VERSION>
#
# Options:
# --remote: Push the created tag to the remote origin.
# major|minor|patch: Increment the respective version component.
# --custom VERSION: Create a custom version tag.
#
# Example Usage:
# Increment the major version and push to remote:
# ./update_version.sh --remote major
#
# Increment the minor version and push to remote:
# ./update_version.sh --remote minor
#
# Increment the patch version and push to remote:
# ./update_version.sh --remote patch
#
# Create a custom version v1.2.3:
# ./update_version.sh --custom 1.2.3
#
# Notes:
# - The script requires Git to be installed and initialized in the repository.
# - When using --custom, VERSION should be in the format x.y.z.
################################################################################
# Author: devinci-it
# Date: 2024
# Version: 1.0
usage() {
echo "Usage: $0 [--remote] <major|minor|patch|--custom VERSION>"
echo " --remote: Push the created tag to the remote origin."
echo " major|minor|patch: Increment the respective version component."
echo " --custom VERSION: Create a custom version tag."
exit 1
}
# Fetch the latest tag
latest_tag=$(git tag --list | sort -V | tail -n 1)
# Parse the latest tag into components
major=$(echo $latest_tag | cut -d '.' -f 1 | sed 's/v//')
minor=$(echo $latest_tag | cut -d '.' -f 2)
patch=$(echo $latest_tag | cut -d '.' -f 3)
echo "Latest version: $latest_tag"
echo "Major: $major"
echo "Minor: $minor"
echo "Patch: $patch"
# Check if at least one argument is provided
if [ $# -lt 1 ]; then
echo "Error: Missing arguments."
usage
fi
# Parse the arguments
case "$1" in
--remote)
shift
action=$1
;;
--custom)
shift
custom_version=$1
;;
major)
action="major"
;;
minor)
action="minor"
;;
patch)
action="patch"
;;
*)
echo "Error: Invalid arguments."
usage
;;
esac
# Perform the action based on the arguments
if [ "$action" = "major" ]; then
major=$((major + 1))
minor=0
patch=0
new_version="v$major.$minor.$patch"
elif [ "$action" = "minor" ]; then
minor=$((minor + 1))
patch=0
new_version="v$major.$minor.$patch"
elif [ "$action" = "patch" ]; then
patch=$((patch + 1))
new_version="v$major.$minor.$patch"
elif [ "$custom_version" ]; then
new_version="v$custom_version"
else
echo "Error: Invalid arguments."
usage
fi
# Prompt for tag message/comment
echo "Enter tag message/comment (Press Ctrl+X to finish):"
tempfile=$(mktemp)
nano "$tempfile"
tag_message=$(cat "$tempfile")
rm "$tempfile"
# Create the new tag with message/comment
git tag -a "$new_version" -m "$tag_message"
echo "Created new tag: $new_version with message: $tag_message"
# Push the new tag to the remote repository if --remote is specified
if [ "$1" = "--remote" ]; then
git push origin "$new_version"
echo "Pushed tag $new_version to origin."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment