Running multiple commands in one line in shell
You are using |
(pipe) to direct the output of a command into another command. What you are looking for is &&
operator to execute the next command only if the previous one succeeded:
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
Or
cp /templates/apple /templates/used && mv /templates/apple /templates/inuse
To summarize (non-exhaustively) bash's command operators/separators:
|
pipes (pipelines) the standard output (stdout
) of one command into the standard input of another one. Note thatstderr
still goes into its default destination, whatever that happen to be.|&
pipes bothstdout
andstderr
of one command into the standard input of another one. Very useful, available in bash version 4 and above.&&
executes the right-hand command of&&
only if the previous one succeeded.||
executes the right-hand command of||
only it the previous one failed.;
executes the right-hand command of;
always regardless whether the previous command succeeded or failed. Unlessset -e
was previously invoked, which causesbash
to fail on an error.
Why not cp
to location 1, then mv
to location 2. This takes care of "removing" the original.
And no, it's not the correct syntax. |
is used to "pipe" output from one program and turn it into input for the next program. What you want is ;
, which seperates multiple commands.
cp file1 file2 ; cp file1 file3 ; rm file1
If you require that the individual commands MUST succeed before the next can be started, then you'd use &&
instead:
cp file1 file2 && cp file1 file3 && rm file1
That way, if either of the cp
commands fails, the rm
will not run.