5

I am trying to make a script that will copy files from a directory and place the copied files into a new directory.

I know that the cp command will copy the files and the mkdir command will create the directory but does anyone know how to combines these 2 commands into a single line?

So far I have

mkdir /root/newdir/ cp /root/*.doc /root/newdir

this gives the error message

mkdir: cannot create directory 'cp': Files exists
mkdir: cannot create directory '/root/files/wp.doc: File exists
mkdir: cannot create directory 'mkdir' : File exists
mkdir: cannot create directory '/root/files/new dir: file exists

However it does create the directory newdir

4 Answers 4

8
mkdir -p /root/newdir/ && cp /root/*.doc /root/newdir/

This will call mkdir to create directory structure, check if command execution was successful and call cp command if it was.

Sign up to request clarification or add additional context in comments.

4 Comments

This works thanks very much although it does come up with the error message... cp: omitting directory 'mkdir'
@user1065861: cp does not copy directories by default. You have to specify -p option if you want it to do so. Check contents of your /root directory - it is likely you have created unintended directories there while playing with those commands.
Thanks to everyone for their help it is now copying fine, however, I am also looking for the command that will take the files from the new directory /root/newdir and replace the files in /root. /root/newdir is basically a backup directory. The command I have so far is.... tar xvzf /root/newdir*.* ;
@user1065861: I'd suggest you ask this question separately. Also, take a look at rsync, it does it for you.
2
mkdir /root/newdir/; cp /root/*.doc /root/newdir

Comments

0

Place semicolon between two commands

Comments

0

This happens because you do not tell the shell where exactly the commands end. In this case:

mkdir /root/newdir/ cp /root/*.doc /root/newdir

Your command cp will go as an argument to the mkdir command and shell tries to make the file named cp. Same happens to all other.

By putting the ; after commands. It tells the shell that command has been ended and next word is an another command.

newline (Return key) is also treated as the command seprator. So if you put each command in next line, it also works fine. So you can try either of these:

mkdir /root/newdir/  ; cp /root/*.doc /root/newdir

OR

mkdir /root/newdir/ 

cp /root/*.doc /root/newdir

1 Comment

Good explanation, but for the solution I prefer && over ; as the former takes care of the possibility of a mkdir failure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.