82

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

0

3 Answers 3

110

One-liner:

[ -f old ] && mv old nu
2
  • 1
    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
    Commented May 20, 2022 at 20:23
  • 2
    @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
    Commented May 22, 2022 at 7:16
89

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

[ ! -f src ] || mv src dest
3
  • 8
    (@mahemoff's version returns false if the file is not found.) Commented Oct 3, 2019 at 5:30
  • 13
    [ ! -d src ] || mv src dest if it's a folder
    – Spidy
    Commented May 1, 2022 at 23:52
  • 2
    I was getting failure notifications in a VS Code tasks running @mahemoff's version. Now I know why. Thanks for the fix. Commented Jan 27, 2023 at 3:13
67

You should test if the file exists

if [ -f blah ]; then
   mv blah destination
fi
5
  • 3
    @Oz123 to be pedantic need to use [ -r blah ], for additional check in read permision
    – SergA
    Commented Oct 29, 2015 at 14:22
  • Only -r worked for me even though the problem was that the file wasn't there at all.
    – Zargold
    Commented Apr 6, 2018 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
    Commented Apr 14, 2018 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.
    – SergA
    Commented Apr 15, 2018 at 13:45
  • 3
    For directories use [ -d myDir ]. Commented Mar 7, 2021 at 19:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.