简体   繁体   English

如何组合shell命令

[英]How to combine shell commands

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? 我知道cp命令将复制文件, mkdir命令将创建目录,但有人知道如何将这两个命令组合成一行吗?

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 但它确实创建了目录newdir

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

这将调用mkdir来创建目录结构,检查命令执行是否成功,如果是,则调用cp命令。

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

This happens because you do not tell the shell where exactly the commands end. 发生这种情况是因为您没有告诉shell命令的确切位置。 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 . 您的命令cp将作为mkdir命令的参数,shell尝试将该文件命名为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. 它告诉shell命令已经结束,下一个字是另一个命令。

newline (Return key) is also treated as the command seprator. 换行符(返回键)也被视为命令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

在两个命令之间放置分号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM