Bash code snippets

Updated: 2024-03-12
2 min read
[Linux Bash Programming Snippets]

Rename all files in current directory / Remove prefix

#!/bin/bash
REMOVE_PREFIX=$1
files=(*)
for file in "${files[@]}"
do
  if [[ $file == *"${REMOVE_PREFIX}"* ]]; then
    # Remove everything before and including the "№" symbol
    new_file=${file##*"${REMOVE_PREFIX}"}
    mv "$file" "$new_file"
    echo "Renamed $file to $new_file"
  fi
done
$ ./rename_files.sh abc

renamed file abc123.txt -> 123.txt

Add substring to filename

#!/bin/bash

DIR="/path/to/folder"
cd "$DIR"

# Rename all .png files and add ".ru" before .png
for file in *.png; do
    base=$(basename "$file" .png)

    mv "$file" "${base}.ru.png"
done

Git Push/Pull for all repos in path

git pull

files=(*)
#!/bin/bash

# For every item in the current directory
for d in */; do
    cd "$d"

    if [[ -d ".git" ]]; then
        echo $d
        git pull
    fi

    cd ..
done

git push

#!/bin/bash

# For every item in the current directory
for d in */; do
    cd "$d"

    if [[ -d ".git" ]]; then
        echo $d
        git add .
        git commit -m "Auto apply"

        # black . # python formatter
        # git add .
        # git commit -m "[chore] formatter"

        git push
    fi

    cd ..
done

git untrack

#!/bin/bash

items_to_untrack=(".idea" ".vscode" ".DS_Store" "__pycache__" "node_modules" ".env" ".serverless")

# For every item in the current directory
for d in */; do
    echo $d
    cd "$d"

    # Iterate over each item to untrack
    for item in "${items_to_untrack[@]}"; do
        # If the item exists
        if [[ -e "$item" ]]; then
            # Untrack the item
            git rm -r --cached "$item"
        fi
    done

    cd ..
done