Linux and Command-Line Basics
$ false && echo A || echo B
$ true || echo C; echo DWhen the two lines above are run in a shell, which of the following are the characters shown?
- AOnly D
- BB and D
- CB, C and D
Show answer and explanation
Answer: B. B and D
Every command returns an exit status when it finishes: 0 means success and anything other than 0 means failure (the last value can be seen with $?). "A && B" runs B only if A succeeds, "A || B" runs B only if A fails, and ";" runs the next command regardless of the result. In the first line false fails, so echo A is skipped, the whole "false && echo A" is treated as a failure, and echo B after || is run. In the second line true succeeds, so echo C is not run, while echo D after ";" always runs, so B and D are shown.
- A. echo B in the first line is also run. After && skips its command, the result is still a failure, so the part after || runs.
- B. Correct. B is shown by the first line and D by the second.
- C. || runs the right-hand command only when the left one fails. true succeeds, so echo C is not run.