BASH Programming

How to Copy a Directory to Another Directory in Bash on Linux

Knowing how to copy a directory is essential for taking backups, migrating the data, organizing the files, and transferring the files remotely. Furthermore, copying a directory to another depends on different factors like directory size, attributes, and the tools that you use for the process. However, Linux beginners sometimes don’t know the correct way to copy a directory to another directory in Bash with no error. So, in this quick blog, we included the simple commands to copy a directory to another directory in Bash on Linux.

How to Copy a Directory to Another Directory in Bash on Linux

It is easy to copy and paste a directory into another directory in Bash, and you can do it using the simple commands in the command line.

Open the terminal and enter the following set of commands to navigate to the parent directory of the directory that you want to copy:

cd /path/to/parent_directory

 

Replace “/path/to/parent_directory” with the actual path of the parent directory that contains the directory that you intend to copy, and let’s call it the source directory. Upon entering the command, you will see that the new command line contains the name of the source directory. Now, copy the current directory through the “cp” command:

cp -r source_directory /path/to/target_directory

 

In place of “source_directory”, input the name of the source directory. Replace the “/path/to/target_directory” with the actual path where you are about to paste the copied directory. The “-r” option explicitly instructs the system to recursively copy the source directory, subdirectories, and other contents.

Let’s take an example where we use a Bash script to copy a directory to another directory. First, run the following commands one by one to create a Bash script and then provide the executable permissions:

touch copy.sh

chmod u+x copy.sh

 

Now, open the script to the nano editor and write the following program in it:

#!/bin/bash

echo "copying a directory"

 

cp -r ~/Documents ~/Music

 

Finally, save the script and then execute it in the terminal.

./copy.sh

 

Once you execute the script, it is time to check the results whether the system has copied the “Music” directory into the “Documents”.

cd ~/Documents

ls

 

Conclusion

Copying a directory to another directory is a fundamental task in Linux, and this short guide explains it using the Bash shell. The overall process is straightforward and it starts with navigating to the parent directory that contains the file that we intend to copy. Finally, we verified if the task was successful.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.