move only if file exists in a shell script
LinuxShMvLinux 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