72

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

100

One-liner:

[ -f old ] && mv old nu
3
  • 7
    this is the sexier answer
    – xdzzz
    Mar 17, 2021 at 20:33
  • 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, 2022 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, 2022 at 7:16
74

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

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

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
    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
    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
    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
    Apr 15, 2018 at 13:45
  • 2
    For directories use [ -d myDir ]. Mar 7, 2021 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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