linuxshmv

Move file only if it exists


I want to use mv to rename a file:

mv src.txt dest.txt

If the file doesn't exist, I get an error:

mv: cannot stat ‘src.txt’: No such file or directory

How do I use mv only if the file already exists?

I don't want to redirect stderr to dev/null as I'd like to keep any other errors that occur


Solution

  • You should test if the file exists

    if [ -f blah ]; then
       mv blah destination
    fi