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?

1
  • 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, 2010 at 21:46

1 Answer 1

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
3
  • 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. Dec 27, 2010 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, 2010 at 21:47
  • Do not forget to place ; before the closing bracket if it is on one line. Mar 27, 2017 at 7:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .