Skip to content

Instantly share code, notes, and snippets.

@icaoberg
Last active January 28, 2025 10:13
Show Gist options
  • Save icaoberg/851840713b107fdfac5fbbf8b1134114 to your computer and use it in GitHub Desktop.
Save icaoberg/851840713b107fdfac5fbbf8b1134114 to your computer and use it in GitHub Desktop.
Rename file with a random filename using uuidgen
#!/bin/bash
# Enable nullglob so patterns that don't match anything expand to null
shopt -s nullglob
# Check if a file name is provided as an argument
if [ -z "$1" ]; then
echo "Error: No file specified. Please provide a file name as an argument."
exit 1
fi
# Assign the first argument to FILE variable
FILE=$1
# Check if the file exists
if [ ! -e "$FILE" ]; then
echo "Error: File '$FILE' does not exist."
exit 1
fi
# Extract the base name (without extension) and all extensions of the file
BASENAME="${FILE%%.*}"
EXTENSIONS="${FILE#*.}"
# Lowercase the EXTENSIONS
EXTENSIONS=$(echo "$EXTENSIONS" | tr '[:upper:]' '[:lower:]')
# Generate a unique file name using uuidgen
NEW_FILENAME="$(uuidgen).$EXTENSIONS"
# Move the file to the new unique file name
mv -v "$FILE" "$NEW_FILENAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment