0

I would like to execute the following command ruby do_task.rb && say "done".

The problem is that it say nothing if the command failed. How to fix it so that it would always say something (I don't mind if it say "failed" instead of "done", or just always say "done").

2
  • stackoverflow.com/a/30508672/469210 Commented Jan 10, 2020 at 11:30
  • 2
    This sintax command && echo ok means - print "ok" if command ended with success. If you wish to print something on fail you should use this command || echo fail or both command && echo ok || echo fail that'll print "ok" on success or "fail" if something went wrong Commented Jan 10, 2020 at 11:47

3 Answers 3

6

Just replace && with a semicolon ;

ruby do_task.rb;say "done"
Sign up to request clarification or add additional context in comments.

1 Comment

I originally voted this down, but after re-reading the question it is a prefectly acceptable answer "or just always say "done""
4

Simply :

(ruby do_task.rb && say "done") || (say "fail")

Or as suggested by @LéaGris to avoid spawning subshells,

{ ruby do_task.rb && say "done";}||say "fail"

Or

ruby do_task.rb; say "end"

7 Comments

I'd suggest replacing parenthesis with curly braces to not spawn extraneous sub-processes: { ruby do_task.rb && say "success";}||say "fail". Note the required space after opening and semicolon before closing curly braces.
@LéaGris thanks for this remark, I didn't know that :)
Also given && (Boolean arithmetic multiplication ×) has priority over || (Boolean arithmetic addition +), curly braces or parenthesis are not needed for this specific order, test this: false && echo "success" || echo "fail", and true && echo "success" || echo "fail".
You forgot the space after { and the semi-colon before the ;}.
Don't use ... && ... || ...; it is not equivalent to if ...; then ...; else ...; fi, which is what you really want.
|
2

Another way using a message array (need shell with arrays) indexed with the return code.

message=('success' 'failure')
ruby do_task.rb
say "${message[$?]}"

Also note that if return code of ruby do_task.rb is greater than 1, you will need an array with messages at indexes for each return codes.

To maintain a binary success or failure with the method above:

message=('success' 'failure')
ruby do_task.rb
say "${message[$(($?>0))]}"

1 Comment

An alternative would be say "${message[$((! ! $?))]}", which I would consider more concise, since the ! ! idiom is used in many programming languages for a similar purpose. Of course this is a matter of taste.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.