bashshell

Running multiple commands in one line in 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?


Solution

  • 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: