27

If I wanted to stay on the same file system, couldn't I just specify an output path for the same file system?

Or is it to prevent accidentally leaving the current file system?

neverMind9
  • 1,690
  • 1
    -x in a different context: https://unix.stackexchange.com/a/358331/30851 but same for cp: -x skips things, if you are migrating filesystems and would like it to be a complete copy, consider mounting in a way that gives you the full picture. – frostschutz Nov 28 '18 at 13:51
  • 1
    You could ask the same about many flags, eg -i: "why not just specify a destination that doesn't exist"? – JigglyNaga Nov 28 '18 at 14:58
  • 1
    @JigglyNaga I was thinking that as well. But -x was not phrased well in the documentation and far less obvious. – neverMind9 Nov 28 '18 at 18:53

2 Answers2

61

It limits where files are copied from, not where they’re copied to. It’s useful with recursive copies, to control how cp descends into subdirectories. Thus

cp -xr / blah

will only copy the root file system, not any of the other file systems mounted.

See the cp -x documentation (although its distinction is subtle).

Stephen Kitt
  • 434,908
  • 3
    Oh yes, you might not want to copy network shares under /mnt. Nor a remote RCS repository mounted under your home drive. – mckenzm Nov 29 '18 at 04:23
  • 1
    @mckenzm Also because /mnt is only a human convention sometimes enforced by a distro's setup but not a requirement of the OS. I sometimes have network filesystems mounted under /var/somewebsite/www/sessions to implement load balancing web servers – slebetman Nov 29 '18 at 15:00
  • Indeed, this kind of flag prevents accidentally copying huge network shares or removable media that you forgot you had mounted. And you don't need to give --exclude options to manually block each of them. Very useful with rsync. – Lassi Nov 29 '18 at 15:08
  • 5
    It also avoids copying file systems such as /dev, /proc, /sys etc. which you typically don’t want to read “en masse”. – Stephen Kitt Nov 29 '18 at 15:09
29

The -x flag to cp is a GNU extension. When copying a single file, this option will have no effect, but when copying a whole file hierarchy, the -x option prevents the copying of files and directories that do not live on the same filesystem as the original source.

For example, on a filesystem with mount points at /usr and /usr/local, using cp -xR /usr /some-dest would not copy the hierarchy under /usr/local.

There are other utilities with an -x option with similar semantics, such as du and find (the flag is called -xdev for find), and rsync.

Kusalananda
  • 333,661