Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running multiple commands in one line in shell

Tags:

bash

shell

Say I have a file /templates/apple and I want to

  1. put it in two different places and then
  2. remove the original.

So, /templates/apple will be copied to /templates/used AND /templates/inuse and then after that I’d like to remove the original.

Is cp the best way to do this, followed by rm? Or is there a better way?

I want to do it all in one line so I’m thinking it would look something like:

cp /templates/apple /templates/used | cp /templates/apple /templates/inuse | rm /templates/apple 

Is this the correct syntax?

like image 727
John Redyns Avatar asked Feb 27 '11 01:02

John Redyns


People also ask

Can 2 commands be used simultaneously in Unix?

The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds. For example, open a Terminal window (Ctrl+Alt+T in Ubuntu and Linux Mint).

Can you have multiple commands on a single line in Linux?

Linux allows you to enter multiple commands at one time. The only requirement is that you separate the commands with a semicolon. Running the combination of commands creates the directory and moves the file in one line.

How do I combine two commands in Linux?

Concatenate Commands With “&&“ The “&&” or AND operator executes the second command only if the preceding command succeeds.


1 Answers

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 that stderr still goes into its default destination, whatever that happen to be.
  • |&pipes both stdout and stderr 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. Unless set -e was previously invoked, which causes bash to fail on an error.
like image 146
Maxim Egorushkin Avatar answered Oct 15 '22 09:10

Maxim Egorushkin