user1065861
user1065861

Reputation: 51

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

Upvotes: 5

Views: 3007

Answers (4)

Yogesh
Yogesh

Reputation: 25

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

Upvotes: 0

rizzz86
rizzz86

Reputation: 3990

Place semicolon between two commands

Upvotes: 0

hmjd
hmjd

Reputation: 122001

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

Upvotes: 2

user405725
user405725

Reputation:

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.

Upvotes: 8

Related Questions