Linux commands
Browse topics

Copying, moving and removing with cp, mv and rm

Version
unversioned
Review
Draft

Summary#

cp copies files, mv renames or moves them, and rm removes them. Directory trees need cp -a or cp -r to copy and rm -r to remove.

Syntax#

sh
cp -a source_dir/. destination_dir/
mv -i -- old_name new_name
rm -r -- directory

-a copies recursively and preserves as much metadata and link structure as it can. -i asks before overwriting.

Example#

sh
(
  set -eu
  export LC_ALL=C
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"
  mkdir src backup
  printf 'port=80\n' > src/app.conf
  printf 'debug=1\n' > src/.env

  cp -a src/. backup/
  cp -a src backup
  find backup -type f | sort

  mv backup/app.conf backup/app.conf.old
  rm -r -- backup/src
  echo '-- after mv and rm -r'
  find backup -type f | sort
)

Expected output#

Text
backup/.env
backup/app.conf
backup/src/.env
backup/src/app.conf
-- after mv and rm -r
backup/.env
backup/app.conf.old

Common mistakes#

cp -a src backup creates backup/src when backup already exists as a directory, but makes backup itself the copy when it does not exist. To copy only the contents, name src/.; the glob src/* skips hidden files. cp and mv can overwrite an existing destination file. Add -i to prompt before replacing it. rm offers no undo, so check the path first, and write "${dir:?}" in scripts so that an empty variable stops the command.

Version applicability#

This entry describes GNU coreutils cp, mv and rm. Other implementations, including BSD, macOS and BusyBox, can differ in options and in what they preserve.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0