25 Feb 2017
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.
None of this is particularly controversial, or even (let's be honest) very interesting.
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
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.
My Shell Scripting books, available in Paperback and eBook formats. This tutorial is more of a general introduction to Shell Scripting, the longer Shell Scripting: Expert Recipes for Linux, Bash and more book covers every aspect of Bash in detail.
![]() Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and in paperback format good to keep by your desk as an ever-present companion. Also available in PDF form from Gumroad:Get this tutorial as a PDF | ![]() Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half covers all of the features of the shell in every detail; the second half has real-world shell scripts, organised by topic, along with detailed discussion of each script. |