Here's a Bash script that takes a list of filenames as input and creates numbered symlinks for them in the format 0001.mp3, 0002.jpg, etc. The script ensures that the numbering is sequential and zero-padded to four digits.
Script: create_numbered_symlinks.sh
bash
#!/bin/bash
# Check if at least one filename is provided
if [ "$#" -eq 0 ]; then
echo "Usage: $0 file1 file2 file3 ..."
exit 1
fi
# Initialize the counter
counter=1
# Loop through all the provided filenames
for file in "$@"; do
# Check if the file exists
if [ ! -e "$file" ]; then
echo "File not found: $file"
continue
fi
# Extract the file extension (if any)
extension="${file##*.}"
# Format the symlink name with zero-padded numbering
symlink_name=$(printf "%04d.%s" "$counter" "$extension")
# Create the symlink
ln -sf "$file" "$symlink_name"
# Increment the counter
counter=$((counter + 1))
done
echo "Numbered symlinks created successfully."
Explanation of the Script:
Input Validation:
The script checks if at least one filename is provided as an argument. If not, it displays a usage message and exits.
Counter Initialization:
A counter variable (counter) is initialized to 1 to track the sequence of symlinks.
Loop Through Filenames:
The script iterates over all the filenames passed as arguments ("$@").
File Existence Check:
For each file, it checks if the file exists using [ ! -e "$file" ]. If the file does not exist, it prints an error message and skips to the next file.
Extract File Extension:
The file extension is extracted using ${file##*.}. This ensures that the symlink retains the original file's extension.
Zero-Padded Numbering:
The printf command is used to format the symlink name with zero-padded numbering (e.g., 0001.mp3, 0002.jpg).
Create Symlink:
The ln -sf command creates a symbolic link (-s) with the formatted name pointing to the original file. The -f flag ensures that any existing symlink with the same name is overwritten.
Increment Counter:
The counter is incremented after processing each file.
Completion Message:
After all files are processed, a success message is displayed.
Usage Example:
Suppose you have the following files in your directory: