CP Linux / Unix Command
If you use linux, you undoubtably have encountered the command cp for copy sometime. Looking at its man page, it seems simple and easy to use:
CP(1) User Commands
NAME
cp - copy files and directories
SYNOPSIS
cp [OPTION]... SOURCE DEST
cp [OPTION]... SOURCE... DIRECTORY
cp [OPTION]... --target-directory=DIRECTORY SOURCE...
Generally this works well, except if you accidentally include a directory in the file list. Let’s set up a test environment:
-bash-3.00$ touch a b d e -bash-3.00$ mkdir c -bash-3.00$ mkdir ../dest
Now, what would you expect if I ran the command to copy all files in the current directory to the ../dest folder? Yes, failure, because c is a directory and not a file–it must be copied recursively or not at all. However, the cp command will simply skip over c and continue copying:
-bash-3.00$ cp * ../dest cp: omitting directory `c' -bash-3.00$ ls ../dest a b d e
This behavior is counterintuitive for me. I would expect it to first validate all of its input arguments, making sure that either a file is being copied to a new file name, a bunch of files to a directory, or some directories recursively to another directory. If these conditions were not met, I would not copy anything! A command which returns a non-zero value (error) should not perform actions on its input, unless it absolutely has to! Clearly cp could check its arguments for errors before processing them–so why doesn’t it, except historical reasons?
| This entry was posted on Thursday, August 24th, 2006 at 7:45 pm and is tagged with cp copy files, target directory, command cp, cp command, input arguments, source dest, directory source, value error, unix command, source directory, zero value, test environment, mkdir, man page, directory directory, failure, linux, unix. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback. |
3 Responses to “CP Linux / Unix Command”
Leave a Reply


Efficiency and offcourse remaining consistent with older versions. If you want to copy files savely and intuitively, use a file browser like nautilus.
“If you want to copy files savely and intuitively, use a file browser like nautilus.”
That’s not a realistic option for remote sysadmin. When I log into a server using ssh, I use cp to move files around.
I can see two reason’s :
1) If you want to make sure that even directories are copied you can put an alias to cp as “cp -R” in you rc script for the shell. But keeping it like this would ensure that atleast files are copied.
2) Since the cp command has been behaving historically like this so a lot of admin’s use it without the “-R” option for copying just the files.