move only if file exists in a shell script

Arth picture Arth · Oct 29, 2015 · Viewed 32.6k times · Source

As part of a backup script I want to call mv on a file to rename it:

mv example.txt example2.txt

If the file doesn't exist, I am receiving the error:

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

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

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

Answer

mahemoff picture mahemoff · Apr 23, 2018

One-liner:

[ -f old ] && mv old nu