When do I use cp --attributes-only

Say you have a file, file1, that you know should have identical attributes to file2 (you know that file2 has the correct attributes).

$ stat file{1,2}
  File: 'file1'
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: 1fh/31d Inode: 2326956     Links: 1
Access: (0600/-rw-------)  Uid: ( 1000/   chris)   Gid: ( 1000/   chris)
Access: 2013-12-24 09:53:20.248720441 +0800
Modify: 2013-12-24 09:53:20.248720441 +0800
Change: 2013-12-24 09:53:31.011984772 +0800
 Birth: -
  File: 'file2'
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: 1fh/31d Inode: 2326957     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/   chris)   Gid: ( 1000/   chris)
Access: 2013-12-24 09:53:21.045382001 +0800
Modify: 2013-12-24 09:53:21.045382001 +0800
Change: 2013-12-24 09:53:21.045382001 +0800
 Birth: -

One way to make sure that they match is to go and check file2 and manually apply the attributes:

$ chmod 644 file1

This is, however, cumbersome to automate and script. It would be easier to get the attributes from file2 and apply them to file1 programatically.

$ cp --attributes-only --preserve file2 file1
$ stat file1
  File: 'file1'
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: 1fh/31d Inode: 2326956     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/   chris)   Gid: ( 1000/   chris)
Access: 2013-12-24 09:53:21.045382001 +0800
Modify: 2013-12-24 09:53:21.045382001 +0800
Change: 2013-12-24 09:57:06.320604649 +0800
 Birth: -

--attributes-only doesn't do anything by itself; it needs to be combined with other attribute preservation flags. From info cp:

--attributes-only
     Copy only the specified attributes of the source file to the
     destination.  If the destination already exists, do not alter its
     contents.  See the `--preserve' option for controlling which
     attributes to copy.

--preserve is used above, which is documented as being equivalent to --preserve=mode,ownership,timestamps. Internally, you can think of this as "don't copy data" rather than "copy attributes only", which is why you have to pass --preserve regardless.

Tags:

Cp

Files