Created
July 23, 2011 20:47
-
-
Save eager/1101864 to your computer and use it in GitHub Desktop.
A bash function for moving a file to a folder, using a sequential rename if the file already exists.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Usage: safe_mv dir1/file.txt dir2 | |
# If dir2 contains "file.txt", the moved file will be renamed to "file1.txt" | |
function safe_mv() { | |
FULL_PATH=$1 | |
FILE_NAME=$(basename $FULL_PATH) | |
FILE_NAME_WITHOUT_EXT=${FILE_NAME%.*} | |
EXT=${FILE_NAME#*.} | |
# Trim any trailing slashes | |
DEST_PATH="${2%/}" | |
if [ -e "$DEST_PATH/$FILE_NAME" ]; then | |
FILE_COUNTER=1 | |
while [ -f "$DEST_PATH/$FILE_NAME_WITHOUT_EXT$FILE_COUNTER.$EXT" ]; do | |
(( FILE_COUNTER=FILE_COUNTER+1 )) | |
done | |
mv "$FULL_PATH" "$DEST_PATH/$FILE_NAME_WITHOUT_EXT$FILE_COUNTER.$EXT" | |
else | |
mv "$FULL_PATH" "$DEST_PATH" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment