Skip to content

Instantly share code, notes, and snippets.

@itsvinayak
Created November 8, 2023 18:39
Show Gist options
  • Save itsvinayak/3489874349b22fdafbf22faa7391d9a6 to your computer and use it in GitHub Desktop.
Save itsvinayak/3489874349b22fdafbf22faa7391d9a6 to your computer and use it in GitHub Desktop.
Sharing a Powerful Bash Script for Streamlined Productivity πŸš€

Open Git Repository:

git remote get-url origin | xargs open

Kill Process by Port:

# lsof -i tcp:8080 | awk 'FNR == 2{print $2}' | xargs kill -9



 function killByPort {
        local port=$1
        echo "killing port ${port}"
        lsof -i tcp:${port} | awk 'FNR == 2{print $2}' | xargs kill -9
        echo "done . . . "
}


killByPort $1


## use : sh killByPort.sh {port}
# port -> 2020, 8000

Backup Script:

#!/bin/bash

function backup {
    local backup_dir="$1"
    local source_dir="$2"

    # Check if source directory/file exists
    if [ ! -e "$source_dir" ]; then
        echo "Error: Source directory/file '$source_dir' not found."
        exit 1
    fi

    # Create backup directory if it doesn't exist
    if [ ! -d "$backup_dir" ]; then
        mkdir -p "$backup_dir"
    fi

    local timestamp=$(date +%Y%m%d%H%M%S)
    local backup_filename="backup_$timestamp.tar.gz"

    tar -czf "$backup_dir/$backup_filename" "$source_dir"
    echo "Backup created: $backup_filename"
}

# Usage: backup <backup_directory> <source_file_or_directory>
backup "./backup" "./example.txt"

Disk Space Checker:

#!/bin/bash

function disk_space {
    local partition=$1
    local disk_space=$(df -h $partition | awk 'NR==2 {print $4}')
    echo "Available disk space on $partition: $disk_space"
}

disk_space /

File Cleanup Script:

#!/bin/bash

function clean_old_files {
    local directory=$1
    local days_old=$2

    find "$directory" -type f -mtime +$days_old -exec rm {} \;
    echo "Old files deleted."
}

clean_old_files "/home/username/Downloads" 30

Find and Replace in Files:

function search_and_replace {
    local search_string="$1"
    local replace_string="$2"
    local directory="$3"
    
    grep -rl "$search_string" "$directory" | xargs sed -i "s/$search_string/$replace_string/g"
    echo "String '$search_string' replaced with '$replace_string' in files under '$directory'."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment