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?

Пока у меня есть

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

5
user1065861 25 Ноя 2011 в 19:11

4 ответа

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

Это вызовет mkdir для создания структуры каталогов, проверки успешного выполнения команды и вызова команды cp, если это так.

8
user405725user405725 25 Ноя 2011 в 19:12
Это работает, большое спасибо, хотя появляется сообщение об ошибке... cp: опуская каталог 'mkdir'
 – 
user1065861
25 Ноя 2011 в 19:15
@ user1065861: cp по умолчанию не копирует каталоги. Вы должны указать опцию -p, если хотите. Проверьте содержимое вашего каталога /root — возможно, вы создали там непреднамеренные каталоги, играя с этими командами.
 – 
user405725
25 Ноя 2011 в 19:17
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
25 Ноя 2011 в 19:28
@user1065861: I'd suggest you ask this question separately. Also, take a look at rsync, it does it for you.
 – 
user405725
25 Ноя 2011 в 19:37
mkdir /root/newdir/; cp /root/*.doc /root/newdir
2
hmjd 25 Ноя 2011 в 19:13

Place semicolon between two commands

0
rizzz86 25 Ноя 2011 в 19:15

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

ИЛИ

mkdir /root/newdir/ 

cp /root/*.doc /root/newdir
0
ByteNudger 22 Янв 2016 в 00:04
Good explanation, but for the solution I prefer && over ; as the former takes care of the possibility of a mkdir failure.
 – 
Henk Langeveld
22 Янв 2016 в 00:20