4

Nearly everybody knows very useful && and || operators, for example:

rm myf && echo "File is removed successfully" || echo "File is not removed"

I've got a question: how to put a block of commands after && or || operators without using the function?

For example I want to do:

rm myf && \
  echo "File is removed successfully" \
  echo "another command executed when rm was successful" || \
  echo "File is not removed" \
  echo "another command executed when rm was NOT successful"

What is the proper syntax of that script?

Arek
  • 155
  • 4
  • 9
  • Even if you can do this, you shouldn't. Use a proper conditional `if/then/else` to make it much easier to read for your self or other people that have to read your script some time in the future. – Zoredache Dec 27 '10 at 21:46

1 Answers1

10
rm myf && {
  echo "File is removed successfully" 
  echo "another command executed when rm was successful"
} || {
  echo "File is not removed" 
  echo "another command executed when rm was NOT successful"
}

or better

if  rm myf ; then
      echo "File is removed successfully" 
      echo "another command executed when rm was successful"
else
      echo "File is not removed" 
      echo "another command executed when rm was NOT successful"
fi
kubanczyk
  • 13,502
  • 5
  • 40
  • 55
  • 1
    The `if` version really is better -- with `cmd && ok || fail`, it can run both `ok` and `fail` (if cmd succeeds, but `ok` finishes with an error condition). `if` always runs either the `then` block or `else` block, never both. Plus, it's much clearer to read. – Gordon Davisson Dec 27 '10 at 17:42
  • +1 The `if` solution is also far more readable. Making scripts readable for future use/re-use is extremely important from a pragmatic standpoint. – Zoredache Dec 27 '10 at 21:47
  • Do not forget to place `;` before the closing bracket if it is on one line. – user3132194 Mar 27 '17 at 07:05