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
@uchuugaka you can do rm -fv and it will output a message if the file was deleted, and it will output nothing if nothing was deleted.
In order to check if a file exists in Bash using shorter forms, specify the “-f” option in brackets and append the command that you want to run if it succeeds. [[ -f <file> ]] && echo "This file exists!" [ -f <file> ] && echo "This file exists!" [[ -f /etc/passwd ]] && echo "This file exists!"
Check if File Exists You can also use the test command without the if statement. The command after the && operator will only be executed if the exit status of the test command is true, test -f /etc/resolv. conf && echo "$FILE exists."
One-liner:
[ -f old ] && mv old nu
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With