Linux copy file and create directory

How to have the cp command create any necessary folders for copying a file to a destination [duplicate]

When copying a file using cp to a folder that may or may not exist, how do I get cp to create the folder if necessary? Here is what I have tried:

[root@file nutch-0.9]# cp -f urls-resume /nosuchdirectory/hi.txt cp: cannot create regular file `/nosuchdirectory/hi.txt': No such file or directory 

@nelaar The age of the question is a secondary concern; the quality and breadth of the answers should be the deciding factor. I don’t have a strong preference either way, but I don’t think it’s worth the effort at this point to turn around the duplicate relationship. If you think otherwise, please offer a rationale (perhaps on meta.stackoverflow.com for proper visibility and process).

Looked for the same thing and could not find my answer below so will post how I ended up doing this: dirname «/nosuchdirectory/hi.txt» | while read path;do mkdir -p «$path»; done && cp -f urls-resume /nosuchdirectory/hi.txt

7 Answers 7

To expand upon Christian’s answer, the only reliable way to do this would be to combine mkdir and cp :

mkdir -p /foo/bar && cp myfile "$_" 

As an aside, when you only need to create a single directory in an existing hierarchy, rsync can do it in one operation. I’m quite a fan of rsync as a much more versatile cp replacement, in fact:

rsync -a myfile /foo/bar/ # works if /foo exists but /foo/bar doesn't. bar is created. 

It’s mentioned in the above answer but I’d like to re-emphasize it (after a few minutes wasted because of not noticing the fine print): The rsync command above is not equivalent to the mkdir/cp command above. It just creates a single level of folder. Actually I’m not sure when it can be useful.

Also, for anyone wondering about the -p argument to mkdir , it’s documented in the POSIX standard at pubs.opengroup.org/onlinepubs/9699919799/utilities/mkdir.html and causes intermediate pathname components to be created (i.e. lets you mkdir foo/bar/baz even if foo or bar don’t already exist).

@PengheGeng : yes, this rsync command can only create one level of folders, but rsync has options to create them all, or only some. rsync: how can I configure it to create target directory on server?

I didn’t know you could do that with cp.

EDIT See lhunath’s answer for incorporating cp.

Hi @KarlMorrison this is an 8 year old question & answer. I also stated that it was for mkdir and not cp.

@Christian I know, it is 2017 and this is the answer directly under the question, which it shouldn’t be. I know that you stated that, however people like me actually looking for an answer regarding the cp command is met with answers like this which have nothing to do with cp prolonging my search for a correct answer. The only answer here which is accurate is stackoverflow.com/a/947971/1137669 he states that cp cannot do it. No one else (including yourself) state that it is not possible with cp .

Читайте также:  Linux как отправить смс

Источник

How to create a directory and copy files into it with bash

I have some files in Pictures\ with extension *.png and directories like 12-21-20, 12-20-20. These directories was created with dir= mkdir $(date +’%m’-‘%d’-‘%Y’) At the end of the day I want to run a script which will create a folder $dir and copy all png files I’ve made for today into that folder. How can I do that? Any information you could give me would be greatly appreciated.

1 Answer 1

date +’%m-%d-%Y’ is the date command outputting, e,g. 12-22-2020 . $(..) is called command substitution that captures the result of the date command allowing it to be assigned to the variable dir .

To create a directory with the contents of $dir (e.g. 12-22-2020 ) you would use the mkdir command, providing the -p option to suppress the error if that directory already exists (and also create parent directories as necessary — not relevant here). You want to ensure it succeeds before you attempt to copy files to the new directory, so you would use:

Which simply exits if the command fails.

At this point, you can simply use cp (or preferably mv to move the files) from whatever source directory they currently reside in. That you can do with:

mv /path/to/source/dir/*.png "$dir" 
cp -a /path/to/source/dir/*.png "$dir" 

Both cp -a and mv will preserve the original file attributes (time, date, permissions, etc. ).

From a script standpoint, you will either want to change to the directory above the new «$dir» or use the full path, e.g.

mv /path/to/source/dir/*.png "/path/to/$dir" 

Short Example

If you want to provide the directory containing the .png files to move to «$dir» created with today’s date, you could write a short script like the following. You provide the directory containing the .png files you would like to copy or move as the first argument to the script on the command-line, e.g. usage would be bash pngscript.sh /path/to/source/dir .

#!/bin/bash [ -z "$1" ] && < ## validate one argument given for source directory printf "usage: ./%s /path/to/images" "$" >&2 exit 1 > [ "$(ls -1 "$1"/*.png | wc -l)" -gt 0 ] || < ## validate png files in source dir printf "error: no .png files in '%s'\n" "$1" >&2 exit 1 > dir=$(date +'%m-%d-%Y') ## get current date mkdir -p "$dir" || exit 1 ## create directory, exit on failure mv "$1"/*.png "$dir" ## move .png files from source to "$dir" 

(note: it will create the «$dir» directory below the current working directory and then move files from the path provided as the first argument (positional parameter) to the newly created directory. Change mv to cp -a if you want to leave a copy of the files in the original directory)

You can make the script executable with chmod +x pngscript.sh and then you can simply run it from the current directory as:

./pngscript.sh /path/to/source/dir 

Let me know if you have further questions.

Источник

Copy and Create Destination Directory if it Does Not Exist in Linux

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.

Читайте также:  Сменить dns сервер linux

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:

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,

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 Copy

Now 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 cp

2. 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.

Now upon giving arguments, the same functionality is executed and the output is below.

Fig 1.4 Execution using Shell Script

3. 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

Fig 1.4 Execution using Install command

There 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.

Источник

Оцените статью
Adblock
detector