Scripts: exit codes

$?, 0 for success, exit n, the conventional codes (1, 2, 126, 127, 128 plus the signal number), the &&, || and ; chains, and a pipeline's code: predicting what a line prints and no longer announcing a false success.

  • 24 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Exit status: what is it?

    Show the answer

    A number from 0 to 255 returned by a command when it ends: 0 signals success, any other value a failure.

    It is the reverse of a language boolean: in the shell, 0 is "true" for if and &&, and any non-zero value is "false".

  • What does this line print?

    ```bash
    false && echo A || echo B ; echo $?
    `

    • B then 0
    • A then 0
    • B then 1
    • A, B then 0
    Show the answer

    B then 0

    false fails, so echo A is skipped and || runs echo B. $? is that last echo's code, which succeeds: 0.

  • A command that cannot be found returns code …; a command found but without execute permission returns ….

    Show the answer

    A command that cannot be found returns code 127; a command found but without execute permission returns 126.

    name: command not found goes with 127, Permission denied goes with 126 when launching directly.

  • The $? variable: what is it?

    Show the answer

    A special variable holding the code returned by the last command that finished, which the next command replaces straight away.

    After grep -q x f; echo $?, you read grep's code. But after an intermediate echo, $? is 0, echo's code: copy it right away.

  • For a backup, the original must only be deleted if the copy succeeded. Which line fits?

    • cp f /backup/ ; rm f
    • cp f /backup/ || rm f
    • cp f /backup/ && rm f
    • cp f /backup/ | rm f
    Show the answer

    cp f /backup/ && rm f

    && only chains after a success. With ;, the original disappears even if the copy fails; with ||, it disappears only if it fails; a pipe runs both in parallel.