'mv foo ..' when . is foo

Guy Harris guy at sun.uucp
Sat Aug 24 15:44:50 AEST 1985


> I just did the following by accident (edited to preserve essential
> point - gh):
> 
> 	mkdir foo		# Make a temporary directory
> 	cd foo
>	>foo
> 	mv foo ..
> 	 .
> 	 .	# Now, what's the name of my current directory?
> 	 .
> 	pwd	# This produces "pwd: read error in .."
> 
> Is this a feature?

Hell, no.  That's a bug.  "mv" should carefully check that it's not
unlinking a non-empty directory; since unlinking the target is the first
operation performed in this move, "foo/foo" should exist and the unlink of
"foo" should be illegal.

4.2BSD, bless its soul, introduced a "rename" system call which

	1) performs the unlink target/link target to source/unlink source
	   operation as one pretty-much-atomic-operation,

	2) is only a rename, and as such doesn't require superuser
	   privileges to rename a directory (since making extra
	   links to a directory is uncool, and unlinking a non-empty
	   directory is *very* uncool, UNIX restricts linking to
	   and unlinking directories to the superuser)

and

	3) checks for all the nasty cases of moving a directory to
	   a subdirectory of itself, etc., so it is safe.

It also doesn't permit you to rename a non-directory if the target to be
removed is a directory, or vice versa; I presume this is a case of
foolproofing.  The above sequence results in

	mv: rename: Not a directory

(or an equivalent but less informative error message if "mv" doesn't use
"perror" or "sys_errlist") on a 4.2BSD system for that very reason.  (And
if it did permit those kinds of mixed renames, it'd say

	mv: rename: Directory not empty

instead.)

Making it a standard library operation also makes it easier to move code to
systems which don't support "link" and "unlink" the way UNIX does, but do
support a "rename" operation.  (The same is true of "mkdir" and "rmdir" -
which are non-privileged system calls in 4.2BSD, so you don't have to "exec"
the "mkdir" or "rmdir" command, which won't work if you're a set-UID program
- and of the directory reading routines.)

	Guy Harris



More information about the Comp.unix.wizards mailing list