Copy and Create Destination Directory if it Does Not Exist in Linux
Last Updated :
05 Jul, 2023
A directory is a file system location for storing and organizing files. A Linux system has many directories, and users can create their own directories. Copying and creating a directory are useful operations for Linux users. To create a new directory, use the command: mkdir new_directory. The 'm' stands for 'modify.' The name of the new directory must follow the 'mkdir' command. The directory created will be empty at first but will soon have additional data stored in it. However, creating a new directory on a system with existing directory conflicts will cause data loss. Therefore, create a new empty directory before copying an existing one.
Create Directory, Copy Files, and Remove Commands
To copy an existing directory to another location, use the following command:
cp old_directory new_directory
The 'c' stands for the copy. The source directory name must precede the destination name in the command. There are two options for moving directories:
- using the mv command
- using the tar command.
Mv (the move) has a greater capacity to move more files at once and also to copy more files with each copy method it uses. On the other hand, tar (the tape archive) extracts files from one location and copies them to another location, hence the name tape archive. It's best to use the method that best suits your needs for that particular operation.
To remove a directory, use the following command:
rmdir new_directory/old_directory
The 'r' stands for remove, and the '/' symbol points to the path of the hidden directory you wish to delete. You cannot delete a system's root or HOME directories; only regular user directories can be removed by using this command. Be sure that you are in the right place when executing this command by knowing where your current directory is located.
Creating a new Linux directory is easy and can be used in many situations. To create a new Linux directory, use the mkdir command or create an empty one before copying an existing one. To copy an existing Linux directory to another location, use the cp command or use archiving methods such as tar or mv to copy a directory onto another drive or partition.
To remove a directory, use the rmdir command or use removing methods such as shredding paper files or overwriting them with zeros by using random-access memory (ram).
In real-world scenarios, we try to move a file to a new folder and we might just need to create the folder manually and then use the cp command to copy it to the destination. Suppose when we are working on an entire project that involves processing and copying files to multiple new subfolders, It is not so feasible to manually keep on creating new directories one by one. In this case, we have to think of a way to automatically create a folder if it doesn't exist and then copy the file. There are 3 ways in which we can achieve this. They are,
- Using mkdir and cp Commands
- Using Shell Script
- Install Package/Command
1. Using mkdir and cp Commands
The Problem statement here is, we are trying to copy Akash.c (from the below example) into a folder under /tmp under Aakaash, which is not created at all. The manual method is by going to that directory via cd and then using mkdir to create the directory. It takes manual effort and is inefficient. Therefore, we must combine mkdir and cp to efficiently solve the problem.
akash:/$ cp $HOME/.Aakaash /tmp/test/one/non-exist/backup/dir/Aakaash
cp: cannot stat '/home/akash/.Aakaash': No such file or directory
akash:/$ ls
bin boot dev etc home init lib lib32 lib64 libx32 lost+found media mnt opt proc root run sbin snap srv sys tmp usr var
akash:/$ cd home
akash:/home$ cd akash
akash:~$ ls
akash linux-5.16.9 linux-5.16.9.tar linux-5.16.9.tar.sign report.xml
akash:~$ cd akash
akash:~/akash$ ls
akash:~/akash$ mkdir Aakaash
akash:~/akash$ ls
Aakaash
akash:~/akash$ cp $HOME/.Aakaash /tmp/test/one/non-exist/backup/dir/Aakaash
cp: cannot stat '/home/akash/.Aakaash': No such file or directory
akash:~/akash$ ls
Aakaash
akash:~/akash$ cd Aakaash
akash:~/akash/Aakaash$ touch Akash.c
akash:~/akash/Aakaash$ ls
Akash.c
akash:~/akash/Aakaash$ cp $HOME/.c /tmp/test/one/non-exist/backup/dir/Aakaash
cp: cannot stat '/home/akash/.c': No such file or directory
akash:~/akash/Aakaash$ cp $HOME/Aakassh/.c /tmp/test/one/non-exist/backup/dir/Aakaash
cp: cannot stat '/home/akash/Aakassh/.c': No such file or directory
akash:~/akash/Aakaash$ cp $HOME/Aakaash/.c /tmp/test/one/non-exist/backup/dir/Aakaash
cp: cannot stat '/home/akash/Aakaash/.c': No such file or directory
akash:~/akash/Aakaash$ cp $HOME/Aakaash/Akash.c /tmp/test/one/non-exist/backup/dir/Aakaash
cp: cannot stat '/home/akash/Aakaash/Akash.c': No such file or directory
akash:~/akash/Aakaash$ cp Akash.c /tmp/test/one/non-exist/backup/dir/Aakaash
cp: cannot create regular file '/tmp/test/one/non-exist/backup/dir/Aakaash': No such file or directory
akash:~/akash/Aakaash$
Fig 1.1 Overall snippet of create and CopyNow to Copy and Create the Destination Directory if it Does Not Exist, we make use of mkdir and cp commands.
Now there are no problems, and using the ls-l command, we can see the directory is created and the file is copied.
Fig 1.2 Copy and Create Destination Directory if it Does Not Exist using mkdir and cp2. Using Shell Script
One more method of Creating and copying files is by using a shell script. The same command is implemented into a script, now that the arguments are from the command line.
Here, the function CPY_GEEKS is created which uses source and destination as arguments from the command line, and the function is saved under function.sh.
Fig 1.3 Function ContentNow upon giving arguments, the same functionality is executed and the output is below.
Fig 1.4 Execution using Shell Script3. Install Package/Command
The Install command is available on All Linux Distributions. The install command is used to uninstall any installed programs or drivers, and can be executed with the default user account 'root'. Determine which Operating System(s) you wish Users running under each operating system should run in place of another program; This may mean they are needed because one has been disabled for performance reasons. You have multiple files (e.) that need to reside in a directory called "~". If this folder isn't present yet there's something wrong: Some users might not want to access their mailboxes via virtual private network-based email servers... so add it now! Click OK then press Enter
There are multiple options available with the install command. The Intended functionality needed is achieved using the -D option.
Command :
install -D Akash.c /tmp/test/one/non-exist/backup/dir/Aakaash
Syntax : install -D <File> <Destination Dir>
Fig 1.4 Execution using Install commandThere are several other ways with which we can Copy and Create the Destination Directory if it Does Not Exist in Linux, out of which combining mkdir and cp commands is the most popular of all because it does not waste CPU cycles. In addition to copying files from directory '..' into destination directories that exist only inside your own system without any modification you may also copy or create an existing folder called $HOME, here "$" stands for a dollar sign so do not worry about capitalization as some programs will treat those numbers accordingly.
Similar Reads
R - Check if a Directory Exists and Create if It does not
Directories and sub-directories are accessed by their corresponding paths in the R Programming Language. It is easy to work with these in R and perform operations related to the creation, copy, and movement of folders and sub-folders within the system. In this article, we will see how to check if a
2 min read
How to Create Directory If it Does Not Exist using Python?
In this article, We will learn how to create a Directory if it Does Not Exist using Python. Method 1: Using os.path.exists() and os.makedirs() methods Under this method, we will use exists() method takes path of demo_folder as an argument and returns true if the directory exists and returns false if
2 min read
How to Copy Files and Directories in Linux | cp Command
The cp (copy) command is your go-to tool in Linux for duplicating files and folders quickly. Whether youâre backing up data, organizing files, or sharing content, cp lets you copy items between locations while keeping the original intact. The cp command requires at least two filenames in its argumen
8 min read
How to Copy a Directory in Linux
There is this famous quote for Linux by Jamie Zawinski that goes like this "Linux is only free if your time has no value." Certainly, that's true as people start using Linux they have to learn more about it, and when encountering it we have to solve it by ourselves, and that way we learn more about
5 min read
How to Create Directory in Linux | mkdir Command
In Linux, the 'mkdir' command is like a magic wand for creating folders super easily. 'mkdir' stands for "make directory," and it helps you organize your computer stuff by creating folders with just one command. Whether you're making one folder or a bunch of them in a row, 'mkdir' is there to help y
7 min read
mkdir: Cannot Create Directory : File Exists
The error "Mkdir: Cannot Create Directory 'Directory': File Exists" occurs when attempting to create a directory using the mkdir command in a Unix-like operating system, but a file with the same name already exists in that location. To resolve this issue, you can either choose a different name for t
3 min read
How to Create a Folder if It Doesn't Exist in PHP ?
We can easily create a folder in PHP, but before that, you have to check if the folder or directory already exists or not. So In this article, you will learn both to Check and Create a folder or directory in PHP. Methods: file_exists(): It is an inbuilt function that is used to check whether a file
3 min read
How to Create a Directory using Node.js ?
In this article, we will create a directory using NodeJS. NodeJS has Filesystem(fs) core module, which enables interacting with the file system, has Node.js fs.mkdir() method or Node.js fs.mkdirSync() method method, to create new directory /parent directory. Prerequisites:Node File SystemThe approac
3 min read
How to Create an Empty File in Linux | Touch Command
The touch command is a standard command used in the UNIX/Linux operating system which is used to create, change and modify the timestamps of a file. Basically, there are two different commands to create a file in the Linux system which are as follows: touch command: It is used to create a file witho
7 min read
How to Copy a File to Multiple Directories in Linux
In this article, we will discuss how to copy a file to multiple directories in Linux. xargs, find, tee, shell loop, and parallel are the commands that can help you to copy a File to Multiple Directories. Suppose we have a file with the name "xyz.txt" and we want to copy it into 3 directories with th
5 min read