To accomplish the task you've described, we will create a bash script that utilizes the gum package for user input and exiftool for image files. If you haven't installed gum yet, you can find installation instructions on its GitHub page: https://github.com/charmbracelet/gum.
First, ensure you have gum and exiftool installed on your system. For Debian-based systems, you can install exiftool using:
sudo apt-get update
sudo apt-get install libimage-exiftool-perl
For gum, follow the installation instructions on its GitHub page.
Here's the script:
#!/bin/bash
# Check if gum and exiftool are installed
if ! command -v gum &> /dev/null; then
echo "gum could not be found. Please install it."
exit 1
fi
if ! command -v exiftool &> /dev/null; then
echo "exiftool could not be found. Please install it."
exit 1
fi
# Get new filename from user
new_filename=$(gum input --placeholder "Enter new filename")
# Check if directory is provided, use current directory if not
directory=${1:-./}
# List files in the directory, sort them by creation time
files=($(ls -rt "$directory"))
# If no files found, exit
if [ ${#files[@]} -eq 0 ]; then
echo "No files found in $directory"
exit 0
fi
counter=1
for file in "${files[@]}"; do
# Skip directories and this script
if [ -f "$directory/$file" ] && [ "$file" != "${BASH_SOURCE[0]}" ]; then
extension="${file##*.}"
filename="${file%.*}"
# Construct new file name
new_file="${directory}/${new_filename}_${counter}.${extension}"
# Rename the file
mv "$directory/$file" "$new_file"
# Check if file is an image and ask to run exiftool
if [[ "jpg png bmp jpeg" =~ ${extension,,} ]]; then
run_exiftool=$(gum confirm "Run exiftool on $new_file?")
if [ "$run_exiftool" = true ]; then
exiftool "$new_file"
fi
fi
((counter++))
fi
done
echo "Files renamed successfully."
How to use this script:
- Save this script to a file, for example,
batch_rename.sh.
- Make the script executable:
chmod +x batch_rename.sh
- Run the script, optionally specifying a directory:
./batch_rename.sh /path/to/directory
If no directory is provided, the script will use the current working directory.
This script does the following:
- Prompts the user for a new filename base.
- Lists files in the specified directory (or current directory if none specified), sorted by their creation time.
- Renames each file, appending a number (starting from
_1) to the provided filename base, preserving the file extension.
- For image files (
.jpg, .png, .bmp, .jpeg), it asks if you want to run exiftool on the renamed file.