Linux and Command-Line Basics

$ false && echo A || echo B
$ true || echo C; echo D

When the two lines above are run in a shell, which of the following are the characters shown?

  1. AOnly D
  2. BB and D
  3. 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.
Practice this topic Back to topic

Books on Linux and Command-Line Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Linux and Command-Line Basics questions

  1. When the commands above are run in order, which of the following is the output of the two echo commands?
  2. As shown above, the script s.sh is run with arguments. Which of the following is the output?
  3. In a shell script, in which of the following cases is the condition of the if above true?
  4. Which of the following are the files in the directory after the session above?
  5. An executable script run.sh in the current directory gives "command not found" when run by typing "run.sh", but runs when typed as "./run.sh". Which of the following is the reason?