77

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

Arth
  • 12,789
  • 5
  • 37
  • 69

3 Answers3

106

One-liner:

[ -f old ] && mv old nu
mahemoff
  • 44,526
  • 36
  • 160
  • 222
  • Note that you have to remember to keep the spaces by the brackets. "[-f old]" not working was a surprise for me, who is more used to whitespace-insensitive languages – jakebeal May 20 '22 at 20:23
  • 1
    @jakebeal True. The `[` here is actually shorthand for `test`, so the rest (before &) are plain old space-separated arguments like you’d pass to any shell command. – mahemoff May 22 '22 at 07:16
79

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

[ ! -f src ] || mv src dest
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
65

You should test if the file exists

if [ -f blah ]; then
   mv blah destination
fi
oz123
  • 27,559
  • 27
  • 125
  • 187
  • 3
    @Oz123 to be pedantic need to use `[ -r blah ]`, for additional check in read permision – SergA Oct 29 '15 at 14:22
  • Only -r worked for me even though the problem was that the file wasn't there at all. – Zargold Apr 06 '18 at 17:38
  • 2
    @SergA, in that particuliar case, wouldn't ````[ -w blah ]```` be more appropriate since ````mv```` needs write permissions over the file? – ghilesZ Apr 14 '18 at 10:51
  • 3
    @ghilesZ, actually there is no need to check write and read file permissions. To move file *you need to have permission to detach it from the directory where it was before, and to attach it to the directory where you're putting it*. Got from [here](https://unix.stackexchange.com/a/149798/170894). – SergA Apr 15 '18 at 13:45
  • 2
    For directories use `[ -d myDir ]`. – Joshua Pinter Mar 07 '21 at 19:26