move only if file exists in a shell script

LinuxShMv

Linux Problem Overview


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

Linux Solutions


Solution 1 - Linux

One-liner:

[ -f old ] && mv old nu

Solution 2 - Linux

You should test if the file exists

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

Solution 3 - Linux

This one liner returns successfully even if the file is not found:

[ ! -f src ] || mv src dest

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArthView Question on Stackoverflow
Solution 1 - LinuxmahemoffView Answer on Stackoverflow
Solution 2 - Linuxoz123View Answer on Stackoverflow
Solution 3 - LinuxMateen UlhaqView Answer on Stackoverflow