Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move only if file exists in a shell script

Tags:

linux

sh

mv

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

like image 253
Arth Avatar asked Oct 29 '15 12:10

Arth


People also ask

How do you check if a file exists and then delete in shell script?

@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.

How do you check if any file exists in a directory in shell script?

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!"

How check file exist in Unix?

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."


1 Answers

One-liner:

[ -f old ] && mv old nu 
like image 84
mahemoff Avatar answered Sep 26 '22 04:09

mahemoff