Skip to content

Instantly share code, notes, and snippets.

@eager
Created July 23, 2011 20:47
Show Gist options
  • Save eager/1101864 to your computer and use it in GitHub Desktop.
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.
#!/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