31

Is it possible to rename the current working directory from within a shell (Bash in my particular case)? If I attempt to do this the straightforward way, I end up with an error:

nathan@nathan-desktop:/tmp/test$ mv . test2
mv: cannot move ‘.’ to ‘test2’: Device or resource busy

Is there another way to do this without changing the current directory? I realize that I can easily accomplish this by changing to the parent directory, but I'm curious if this is necessary. After all, if I rename the directory from another shell, I can still create files in the original shell afterwards.

3 Answers 3

43

Yes, but you have to refer to the directory by name, not by using the . notation. You can use a relative path, it just has to end with something other than . or ..:

/tmp/test$ mv ../test ../test2
/tmp/test$ pwd
/tmp/test
/tmp/test$ pwd -P
/tmp/test2

You can use an absolute path:

/tmp/test$ cd -P .
/tmp/test2$ mv "$PWD" "${PWD%/*}/test3"
/tmp/test2$ 

Similarly, rmdir . won't ever work, but rmdir "$PWD" does.

2
  • Perfect... exactly the answer I was hoping for. Commented Mar 4, 2015 at 0:32
  • 5
    The basic issue is that you're not allowed to remove or rename the special "." and ".." names.
    – Barmar
    Commented Mar 4, 2015 at 19:26
3

As in @Gilles answer but using brace expansion for brevity:

mv ../{test,test2}
1

And it depends on how you define “changing the current directory”.

/tmp/test$ (cd .. && mv test test2)
/tmp/test$ pwd
/tmp/test
/tmp/test$ pwd -P
/tmp/test2

spawns a subshell and changes the current directory in the subshell, but leaves your primary shell where it was.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .