cp Omitting Directory

When using the cp command, it's common to want to copy the contents of a source directory into an existing destination directory, rather than creating a new subdirectory with the same name as the source. This guide explains how to achieve that.

Syntax

cp -r SOURCE_DIRECTORY/. DESTINATION_DIRECTORY/
cp -r SOURCE_DIRECTORY/* DESTINATION_DIRECTORY/

Description

By default, when you copy a directory using cp -r source_dir destination_dir, it creates destination_dir/source_dir/ and places the contents inside. To avoid this nested directory and copy the contents directly into destination_dir, you need to explicitly tell cp to copy the contents of the source directory, not the directory itself.

This is typically done by:

  • Appending /. to the source directory name.
  • Appending /* to the source directory name (for non-hidden files).

Examples

Copy contents using /. (recommended)

mkdir /tmp/destination_folder
mkdir /tmp/source_folder
echo "hello" > /tmp/source_folder/file.txt
cp -r /tmp/source_folder/. /tmp/destination_folder/
ls /tmp/destination_folder/
# Output: file.txt

This method copies all contents, including hidden files, directly into the destination.

Copy contents using /* (excludes hidden files)

mkdir /tmp/destination_folder2
mkdir /tmp/source_folder2
echo "hello" > /tmp/source_folder2/file.txt
echo "hidden" > /tmp/source_folder2/.hidden_file.txt
cp -r /tmp/source_folder2/* /tmp/destination_folder2/
ls -a /tmp/destination_folder2/
# Output: . .. file.txt (hidden_file.txt is not copied)

This method copies non-hidden contents directly into the destination.

Incorrect usage (creates nested directory)

mkdir /tmp/destination_folder3
mkdir /tmp/source_folder3
echo "hello" > /tmp/source_folder3/file.txt
cp -r /tmp/source_folder3 /tmp/destination_folder3
ls /tmp/destination_folder3/
# Output: source_folder3 # (Contents are in /tmp/destination_folder3/source_folder3/file.txt)

This shows the default behavior where a new subdirectory is created.

⚠️ Important Notes

  • Always ensure the destination directory exists before using /. or /*.
  • Using /* will NOT copy hidden files (those starting with a dot). Use /. to include hidden files.
  • Be careful with destination paths to avoid unintended overwrites.

See also