mv: prompt to rename or overwrite

Viewed 2122
find /home/csuser/testfiles . -type f -name "*.c" -exec mv '{}' /home/csuser/src/ \;

The above command will simply overwrite files which have the same name. How can I make mv prompt me to either overwrite the existing file or replace it, for each file name which already exists at the target?

2 Answers

The manpage of the mv command (man mv) shows the following entry:

       -i, --interactive
              prompt before overwrite

So, using mv -i ... prompts before overwriting.

Here's a simple shell script wrapper to prompt you for each existing file.

find /home/csuser/testfiles . -type f -name "*.c" -exec sh -c '
    for file; do
        dest=$0/${file##*/}
        if [ -e "$dest" ]; then
            ls -ld "$dest" "$file"
            read -p "Enter new name for the second, or just ENTER to overwrite the first: " newname
            if [ "$newname" != "" ]; then
                dest=$0/${newname##*/}
            fi
        fi
        mv "$file" "$dest"
    done' /home/csuser/src/ {} +

We obscurely but conveniently pass in the destination directory as $0.

Related