Skip to content

Instantly share code, notes, and snippets.

@sebastiancarlos
Last active March 9, 2024 14:38
Show Gist options
  • Save sebastiancarlos/21d7db76d1ed242cb9246f63f7a31d21 to your computer and use it in GitHub Desktop.
Save sebastiancarlos/21d7db76d1ed242cb9246f63f7a31d21 to your computer and use it in GitHub Desktop.
bkp - toggle ".bkp" extension
#! /usr/bin/env bash
# All my gist code is licensed under the MIT license.
# Add this somewhere in your .bashrc
# bkp
# - toggle a ".bkp" extension to a file(s)
function bkp () {
# print usage on -h/--help or no arguments
if [[ "$#" -eq 1 && ("$1" == "-h" || "$1" == "--help") ]]; then
echo "${bold}Usage:${reset} bkp <file>..."
echo " - If the file has a '.bkp' extension, remove it"
echo " - If the file does not have a '.bkp' extension, add it"
echo " - Do nothing if a file with the new name already exists"
return 1
fi
# first, create array of all the final files
local newFiles=()
for file in "$@"; do
if [[ "$file" == *.bkp ]]; then
newFiles+=("${file%.bkp}")
else
newFiles+=("${file}.bkp")
fi
done
# bail out if any of the new files already exists
for file in "${newFiles[@]}"; do
if [[ -f "$file" ]]; then
echo "${red}Error:${reset} This script would overwrite ${bold}$file${reset}. Bailing out."
return 1
fi
done
# rename files
local index=0
for file in "$@"; do
mv "$file" "${newFiles[$index]}"
index=$((index + 1))
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment