bug-fileutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: "cp" behaves strangly when overwriting a file


From: Bob Proulx
Subject: Re: "cp" behaves strangly when overwriting a file
Date: Wed, 16 Apr 2003 21:34:03 -0600
User-agent: Mutt/1.3.28i

Herv? Pag?s wrote:
> It seems that overwriting an existing file with "cp" doesn't
> exactly replace the old one by the new one but preserves the
> old one and only replaces its content!

That is correct.

> Ownership and mode have been preserved! Only content and
> mtime have changed.

Yes.  That is the way UNIX and UNIX-like systems work.

> I just wonder if this is a normal behaviour...

Yes.  It has been that way for 30 years.  And the behavior is there by
design.  It has many advantages.  As well as some disadvantages too.
But so it is.  This is a behavior of the operating system upon which
the 'cp' command is running.  It is not a function of the 'cp' command
itself.

GNU coreutils have an extension 'cp -b' that will move the file to a
backup just prior to writing the new file.  That might be of interest
to you.  You will then own the new file and the old file will be left
as backup.  Also look at --remove-destination which unlinks the file
just prior to writing it, thereby each copy is a new file.  But again,
those are extensions and not available on "standard" systems.

Here is some background which might help you.  When files get created
they are assigned an inode which is a data structure on disk to hold
the attributes of the file.  Actually it is more accurate to say that
creating an inode is the process of creating a file.  All of the disk
blocks are chained through the inode.  Therefore the inode is really
the file as we think of them.  The disk space is linked through the
inode.

When you create a file you are creating the inode and therefore you
own it.  The permissions are stored in the inode.  When you copy on
top of an exising file the filesystem does not need to create a new
file.  It already has an existing file.  The operation of open(2) for
writing starts writing at the start of the file and proceeds until
close(2).  At that point the file is truncated and any extra disk
space is freed.  If more disk space is needed then the filesystem
allocates it and extends the file.

The 'ls -i' option will list the inode number.  Try 'ls -ldi file'
both before and after the copy.  You will find that the inode number
is not changing.

Hope this helps.

Bob




reply via email to

[Prev in Thread] Current Thread [Next in Thread]