0

In bash, is it possible to use these two operators to handle both of the exit statuses of the same command ? or if I want to handle both cases, I have to use an if statement ?

3

Yes, It's possible

[[ "a" == "a" ]] && echo true || echo false

Try replacing "a" with "b", to see false:

[[ "b" == "a" ]] && echo true || echo false
  • Yes and no: [[ "a" == "a" ]] && /bin/false || echo false gives "false", which may or may not be useful if you just want to look at the exit status of the first command. – Ulrich Schwarz Apr 27 '16 at 12:56
  • @Ulrich: Dani_l's answer is right. Your comment is obviously always false since anything && false will be false on any system or language. That's just basic logic. – Julie Pelletier Apr 27 '16 at 13:07
  • in bash , the && operator is not a logical and, it means that it will execute the command found on the right side of the operator, if the left side was executed with success – mazs Apr 27 '16 at 15:28
  • The same way, the || operator will execute the command on it's right side if the command on it's left side fails. – mazs Apr 27 '16 at 15:38
  • @JuliePelletier: yes, which is my point exactly: if the success handler echo true should ever fail itself, the failure handler echo false is executed, even if the original command was successful. – Ulrich Schwarz Apr 27 '16 at 17:54
1

This is the closest you can get:

your_main_command && run_on_success || run_on_failure

The caveat is that run_on_failure will be run if any of the preceding commands i.e. you_main_command or run_on_success fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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