Advanced File Copying Options
In this step, you will learn about some useful options of the cp
command that can make your file copying tasks more efficient.
Let's start by navigating back to the project directory:
cd ~/project
Preserving File Attributes with -p
When you copy files, you might want to preserve the original file's attributes such as timestamps, ownership, and permissions. The -p
option allows you to do this:
cp -p data-files/apple.txt backup/apple_preserved.txt
Let's compare the original file and the preserved copy:
ls -l data-files/apple.txt backup/apple.txt backup/apple_preserved.txt
You'll notice that backup/apple_preserved.txt
has the same timestamp as the original file, while backup/apple.txt
(which we copied earlier without the -p
option) has a newer timestamp.
Creating Recursive Copies with -r
To copy directories along with their contents, you need to use the -r
(recursive) option. Let's create a nested directory structure to demonstrate this:
mkdir -p data-files/nested/deep
echo "This is a nested file." > data-files/nested/nested_file.txt
echo "This is a deep nested file." > data-files/nested/deep/deep_file.txt
Now, let's copy the entire data-files
directory and its contents to a new location:
cp -r data-files data-files-backup
Let's verify that the directory structure and files were copied correctly:
find data-files-backup -type f | sort
You should see output listing all the files in the copied directory structure:
data-files-backup/apple.txt
data-files-backup/grape.txt
data-files-backup/nested/deep/deep_file.txt
data-files-backup/nested/nested_file.txt
data-files-backup/orange.txt
Interactive Mode with -i
When copying files, you might accidentally overwrite existing files. The -i
(interactive) option prompts you before overwriting any file:
cp -i data-files/apple.txt backup/apple.txt
Since backup/apple.txt
already exists, you'll see a prompt asking if you want to overwrite it:
cp: overwrite 'backup/apple.txt'?
You can respond with y
to overwrite or n
to cancel.
These advanced options make the cp
command even more powerful and flexible for your file management needs.