How to use 'cp' command to exclude a specific directory
The cp command is used to create an exact copy of the contents of files and directories but with a different name and location. It works using the terminal.
Syntax
cp [source_file/directory] [destination]
Where cp is used for the copy, source_file provides the exact file or directory or folder from where you want to copy the contents; destination provides the location where you want to copy the file.
Basic Example
To copy the contents of a file to another file in the same directory using the "cp" command:
Step 1: We will list all the files and directories using the ls command.
ls

Step 2: Create a file f1.txt and display its contents using the cat command.
cat > f1.txt
Hello, this is a sample file.
Press : Ctrl + D

Step 3: If we want to copy the file in the same directory, we use the following syntax:
cp f1.txt f2.txt

Here, the contents of file1 is copied to file2.
Step 4: To check that, type the ls command
ls

Step 5: To find out the contents of file2.txt,
cat f2.txt

Key Options for the cp Command
We will enlist brief working of all the commands utilized for our example:
Command | Usage |
---|---|
cd | To change the directory from the current directory
|
mkdir | Will make a directory/folder in the current folder. We can create multiple directories in the same line separated by space. Ex: mkdir d1 d2 d3 |
ls | Will list all the files and directories in the current one ls -A will list all files and directories including the hidden one (starting with ".") |
cat | Will create a new file
|
cp | Copy command Copies the contents of one file to another in either the same or the other directory |
Usage of the cp command to exclude a specific directory
Example: To copy all the files from one directory to another except a specific one using cp command:
Step 1: Let's create 2 empty directories: source (src) and destination (dest).
mkdir src dest
ls

Step 2: Change the directory to src using cd command and create two files f1.txt and f2.txt in the src directory using the cat command.
cd src
cat > f1.txt
This is file 1
Press : Ctrl + D
cat > f2.txt
This is file 2
Press : Ctrl + D

Step 3: Check the contents of the dest using the ls command. Currently, it has 0 files/folders.
cd ..
cd dest
ls

Step 4: Now use the cp command to copy all files and folders from src except f2.txt to the folder dest.
cp src/(!f2.txt) dest
ls dest
copy all files and folders from src except f2.txt to the folder dest
Conclusion
The cp command is a powerful tool for copying files and directories in Linux. By using various options and techniques, you can exclude specific files or directories from being copied, making it a versatile command for file management tasks.