Linux Commands Examples

A great documentation place for Linux commands


copy files and directories



add an example, a script, a trick and tips

: email address (won't be displayed)
: name

Step 2

Thanks for this example ! - It will be moderated and published shortly.

Feel free to post other examples
Oops ! There is a tiny cockup. A damn 404 cockup. Please contact the loosy team who maintains and develops this wonderful site by clicking in the mighty feedback button on the side of the page. Say what happened. Thanks!


cp .vimrc ~/
cp .bashrc ~/
cp ./.bashrc ~/
cp ./.vimrc ~/
cp ./.inputrc ~/
cp ./.gitconfig ~/
cp ./.screenrc ~/
cp ~/.bashrc ./
cp ~/.vimrc ./
cp ~/.inputrc ./
cp ~/.gitconfig ./
cp ~/.screenrc ./
cp $*
cp .vimrc ~/.vimrc
cp -r .vim ~/.vim
cp .zshrc ~/.zshrc
cp .screen ~/.screen
cp .screenrc ~/.screenrc
cp .vimrc ~/.vimrc
cp .zshrc ~/.zshrc
cp .gitconfig ~/.gitconfig
cp .vim ~ -R
cp .vimrc ~
cp .gvimrc ~

How to copy symbolic links?

Just as the man page says, use -P.


Copy file in GNU/Linux with progress bar and rate limiting

I suggest you check this out:

It looks rather neat! =)


How can I recursively copy files by file extension, preserving directory structure?

how about you first copy it over with

cp -r /old/folder /new/folder

then go to the new folder and run

find . -type f ! -iname "*.txt" -delete

or just

cp -r /old/folder /new/folder && find . -type f ! -iname "*.txt" -delete

Edit: ok you want one command which filters (I have not tested this because my system doesn't have the cpio command!). Here is where I found it:

find . -name "*.txt" |
     cpio -pmd0 /dest-dir

Please test this first, because I haven't tried it yet. If someone would verify, that would be great.


Linux copy to fat32 filesystem: invalid argument

The usual suspects when you want complex copies or renames are GNU cp, zmv from zsh, rsync and pax (or cpio). There's no rename feature in cp, nor (I think) in rsync. While zmv can rename, this doesn't mesh well with recursive copies. But pax can do it:

cd /ext3
pax -rw -s '/[*?:]/_/gp' stuff /fat32/partition

This changes each *?: to _. Warning: minimally tested. If there are collisions, whichever file is copied last wins.


Why does du -sl show different sizes for the source and result of a cp -rl?

Just tried this myself, and I found the discrepancy in size is from the directory files. Since they are not hardlinked they are new files that get created, maybe not with the exact same metadata?

To illustrate this run the following commands:

ls -alR folderA/ | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
ls -alR folderB/ | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'

These sizes should be identical (dir files not included). You could print the listings with the directory sizes and diff the results to find which dirs exactly are different.


How is install -c different from cp

The install utility, at its base, is a fancy cp. But as a tool specifically do installs it contains a few features that cp doesn't. My /usr/bin/install from GNU coreutils not only copies, but also can change perms/ownership as arg flags (saving chgrp, chown, chmod invocations) an option to strip debug info (saving a strip invocation) and also some mojo for SELinux contexts.

It just provides convenience actions useful for software installs. None are life changing, all are useful, and make your scripts cleaner.


Copying files with SSH

This isn't really programming related, but you can use scp to do this.

scp remote-box-name:/path/to/destination/

If your username is different on the remote box, you will need to prefix it:

scp yourusername@remotebox:/path/to/destination/

How can I copy a (big) directory over another changing only the files that differ?

You can use rsync to do this, the command I use is rsync -tr "folder to copy from" "folder to copy to"

e.g. rsync -tr /home/me/stuff/* /home/me/otherstuff/


Multi-core and copy speed

Your bottleneck is hard-drive speed. Multi-core can't speed this up.


How to copy symlinks to target as normal folders

cp -Lr /usr/share/solr/ ~/solrTest

Check the man page for unix commands with man cp

   -L, --dereference
          always follow symbolic links in SOURCE

How do you use regular expressions with the cp command in Linux?


The cp command does not possess the capability to process any of its arguments as regular expressions. Even wildcards are not handled by it (or most executables); rather they are handled by the shell.

cp test/* test2/ is actually expanded by bash, and all that cp really sees for its arguments are cp test/file1 test/file2 test/file3 test2/ (or whatever is appropriate based upon the actual contents of test/).

Also, I don't think your expression, [^\.php], will match what you want it to (it doesn't match only files that contain .php).

You probably want to look into the find utility to filter out a list of files based upon regular expression, and then use xargs to apply the returned file list to the cp command (presuming find doesn't have a built-in handler for copying files; I'm not intimately familiar with the tool).

You might try:

find . ! -iregex ".*\.php.*" -exec cp {} /destination/folder/ \;

This says to search the current directory recursively for files which do not contain ".php" in the path and copy them into /destination/folder/.

As requested, a more specifc breakdown of the arguments:

  • . - Location to start the search - in this case, the current directory
  • ! - "Not" operator, invert the result of the next test
  • -iregex - Case-insensitive regular expression test. Next argument is the expression.
  • ".*\.php.*" - Regular expression matching <Anything>.php<Anything> - Any file that has ".php" somewhere in the path. (Note, including being inside a folder which contains ".php" in the name, you'd need a more complex expression to match only the files)
  • -exec - Execute a command if the preceding tests return true. Next argument is the command, all remaining arguments up to ; are passed to the command. the {} is a special argument representing the filename.
  • cp - The command that find` should run on each of the matched path names.
  • {} - The path to the file that was found, passed to cp as an argument so that it knows what file to copy
  • /destination/folder/ - argument passed to cp, telling cp where it should copy the file to.
  • \; - This is the ; terminator that -exec is looking for. We escape it with a \ so that your shell doesn't try to parse it and instead feeds it as an argument to the command (find)

It's rather difficult to write a regular expression which matches "strings that do not have .php", so we instead tell find to search for strings that do contain .php and then invert the results with !.


Linux permissions and owner being preserved with cp

I don't get a prompt to overwrite. Why not?

Because you're supposed to know what you're doing. Especially as root, you can overwrite pretty much anything, so pay attention to that.

Use the -i option for cp to get a prompt before overwriting existing files. If you always want to be reminded of this, consider creating an alias for cp to cp -i.

The permissions are unchanged. But if […] file someFile does not exist it is owned by root and not user. Why?

Because the file you're copying to is already existing. It's not deleted and re-written. It's still owned by user.

However, check cp's -p option. It will preserve the attributes of the source file, namely the mode, ownership and timestamps. Otherwise, the mode and ownership attributes of the target file will stay (except for the timestamps which will indicate a modification).

If there's no target file, obviously the attributes of the source file need to be copied, since they can't be inherited from a target file. You'll basically just create a new file, and in this case it's owned by root.


how to stop cp: overwrite './xxx' ? prompt

After seeing this solution. I could see that bashes alias feature was causing the problems.

which cp  
alias cp='cp -i'
which cp | grep cp
alias cp='cp -i'

He recommends

unalias cp

I still want to keep the alias I just don't want it to apply to this instance. My solution is to use the binary with a full path, so that bashes alias function does not take over. That works quite well.

/bin/cp -f /media/somedir/somefiles* .  

Linux: Copy all files by extension to single dirrectory

Use find for this find . -name "*.TIF" -exec cp {} new \;

So find is used to find files. The command is saying find files starting from here . where the name of the file -name ends in .tif remember the double quotes for shell expansion. So to find all the tif files is simply.

find . -name "*.tif"

We then use -exec to do something with files in this case cp found files {} to the target directory new followed by an escaped semicolon \;


Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

Mandatory arguments to long options are mandatory for short options too.
, --archive

same as -dR --preserve=all


don’t copy the file data, just the attributes


make a backup of each existing destination file


like --backup but does not accept an argument


copy contents of special files when recursive


same as --no-dereference --preserve=links

-f, --force

if an existing destination file cannot be opened, remove it and try again (redundant if the -n option is used)

-i, --interactive

prompt before overwrite (overrides a previous -n option)


follow command-line symbolic links in SOURCE

-l, --link

hard link files instead of copying

-L, --dereference

always follow symbolic links in SOURCE

-n, --no-clobber

do not overwrite an existing file (overrides a previous -i option)

-P, --no-dereference

never follow symbolic links in SOURCE


same as --preserve=mode,ownership,timestamps


preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all


don’t preserve the specified attributes


use full source file name under DIRECTORY

-R, -r, --recursive

copy directories recursively


control clone/CoW copies. See below


remove each existing destination file before attempting to open it (contrast with --force)


control creation of sparse files. See below


remove any trailing slashes from each SOURCE argument

-s, --symbolic-link

make symbolic links instead of copying

-S, --suffix=SUFFIX

override the usual backup suffix

-t, --target-directory=DIRECTORY

copy all SOURCE arguments into DIRECTORY

-T, --no-target-directory

treat DEST as a normal file

-u, --update

copy only when the SOURCE file is newer than the destination file or when the destination file is missing

-v, --verbose

explain what is being done

-x, --one-file-system

stay on this file system


display this help and exit


output version information and exit

By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files.

When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy.

The backup suffix is ’~’, unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values:
none, off

never make backups (even if --backup is given)

numbered, t

make numbered backups

existing, nil

numbered if numbered backups exist, simple otherwise

simple, never

always make simple backups

As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file.


Copyright © 2012 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <>.
This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.

reporting bugs

Report cp bugs to bug-coreutils[:at:]gnu[:dot:]org
GNU coreutils home page: <>
General help using GNU software: <>
Report cp translation bugs to <>

see also

The full documentation for cp is maintained as a Texinfo manual. If the info and cp programs are properly installed at your site, the command

info coreutils 'cp invocation'

should give you access to the complete manual.


Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering.

How can this site be more helpful to YOU ?

give  feedback