Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question
    
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
add comment

1 Answer

up vote 6 down vote accepted
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
share|improve this answer
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.