1

command1 && command2 && echo "OK" || echo "FAIL"

This will print OK if both commands succeeded or FAIL if either of commands failed.

How can I modify this to print:

  • OK if both commands succeded,
  • FAIL 1 if command1 failed, and
  • FAIL 2 if command2 failed?
0

3 Answers 3

0

Using curly braces to group commands (without creating a subshell) will work:

command1 && { command2 && echo OK || echo FAIL2 } || echo FAIL1

Note that if command1 fails, command2 won’t be run so you’ll just get FAIL1.

I also think that this construction is not very readable. I find using && works well for simple cases but for more complicated conditionals, I prefer to use if statements.

0

There are many ways, for example:

if ! command1; then
    echo 'FAIL 1'
elif ! command2; then
    echo 'FAIL 2'
else
    echo 'OK'
fi

If the point is just to quickly debug a Bash script consider using the -x option:

Print commands and their arguments as they are executed.

0

You can also define a variable (a) and write only at the end which was the failed command

 a=1 && cmd2 && a=2 && cmd1 && a=0 && echo ok || echo fail $a

You can use that value later in the script... for this reason after the last command you can reset the value to 0.

not elegant but somehow it works. :-)

You must log in to answer this question.

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