25th Feb 2017
The 'cp -t' command
A rant
The "cp" command is familiar to most UNIX and Linux users, it is one of the first that you learn. It copies the file (or files) given
to it, to the target location, which is the last file name in the list.
So, the command:
$ cp file.txt file.bak
will copy the file.txt file to a backup named file.bak, while this:
$ cp /etc/hosts /tmp
will copy the /etc/hosts file to the /tmp directory.
If copying to a directory, you can also give cp a list of files to copy, such as:
cp /etc/hosts /etc/passwd /tmp
which will
copy /etc/hosts and /etc/passwd to the /tmp directory.
So What?
None of this is particularly controversial, or even (let's be honest) very interesting.
Because of this!
Where it gets interesting, is with the "cp -t" switch. This tells cp that the file (or directory) name directly after -t is the target, which is where all of the file(s) listed, are to be copied to. That breaks the normal understanding of what the order of "cp" arguments mean.
So "cp -t /tmp /etc/hosts" is another way to copy /etc/hosts to /tmp:
$ cp -t /tmp /etc/hosts
There is no need for that switch, which reverses the order of the "from" and "to" parts of the command. But this is the truly evil part:
cp a b c -t targetdir d e f
will copy the files a,b,c as well as d,e,f to the target directory named targetdir. That is a really nasty, unreadable kind of a command.
# Copy /etc/hosts to /tmp $ cp /etc/hosts /tmp # Copy a,b,c,d,e and f to /tmp $ cp a b c d e f /tmp # Why, oh why?! $ cp a b c -t /tmp d e f
Update: A use has been found
A few people have contacted me to point out that, when used alone, the "cp -t" command can be useful:
$ find /foo -name "*.c" -print0 | xargs -0 cp -t /tmp
Please, never use the "cp -t" form of the command other than for this, where at least it is clear that cp is not being used in its traditional form.
Invest in your career. Buy my Shell Scripting Tutorial today: