简体   繁体   中英

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?

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

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

在两个命令之间放置分号

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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