Bird
0
0

You want to run two commands in a script: cmd1 and cmd2. You want to run cmd2 only if cmd1 succeeded (exit code 0). Which is the best way to do this?

hard🚀 Application Q15 of 15
Bash Scripting - Error Handling
You want to run two commands in a script: cmd1 and cmd2. You want to run cmd2 only if cmd1 succeeded (exit code 0). Which is the best way to do this?
Acmd1 && cmd2
Bcmd1 || cmd2
Ccmd1; if [ $status -eq 0 ]; then cmd2; fi
Dif [ cmd1 ]; then cmd2; fi
Step-by-Step Solution
Solution:
  1. Step 1: Understand conditional execution operators

    The operator && runs the second command only if the first succeeds (exit code 0).
  2. Step 2: Compare options for best practice

    cmd1 && cmd2 uses cmd1 && cmd2 which is concise and reliable for this purpose.
  3. Final Answer:

    cmd1 && cmd2 -> Option A
  4. Quick Check:

    Use && to run second command only if first succeeds [OK]
Quick Trick: Use && to run next command only if previous succeeds [OK]
Common Mistakes:
MISTAKES
  • Using || which runs second if first fails
  • Checking $? manually when && is simpler
  • Using if with command but less concise

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes