Scripts: tests and conditions

if, elif, else and fi, the test command and its [ ] form, file, string and number tests, the &&, || and ! operators, and case: choosing the branch a script runs and spotting a badly written test.

  • 27 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

  • The test command: what is it?

    Show the answer

    A command that evaluates a condition without printing anything and answers through its exit code: 0 if it is true, 1 if it is false. It can also be written between brackets.

    [ is a real command: the spaces around the brackets are mandatory, and [-f x ] gives [-f: command not found.

  • This script is launched with ./age.sh 18. What does it print?

    ```bash
    age=$1
    if [ "$age" -gt 18 ]; then
    echo majeur
    elif [ "$age" -ge 12 ]; then
    echo ado
    else
    echo enfant
    fi
    `

    • ado
    • majeur
    • enfant
    • ado then enfant
    Show the answer

    ado

    -gt is strict: 18 is not greater than 18, so the first branch is skipped. -ge 12 is true, and only that branch runs.

  • An if construct continues with … after the condition and ends with …; the optional else branch goes before that last word.

    Show the answer

    An if construct continues with then after the condition and ends with fi; the optional else branch goes before that last word.

    fi is if spelled backwards, like esac for case.

  • The if construct: what is it?

    Show the answer

    A statement that tries its conditions in order and runs only the first branch whose condition command returns code 0, or else its default branch if it has one.

    The condition is not a boolean but any command: if grep -q pattern f; then works with no brackets at all.

  • The backup script must only continue if the file $1 exists and it was given exactly 2 arguments. Which test fits?

    • [ -f "$1" ] || [ $# -eq 2 ]
    • [ -f "$1" ] && [ $# -ge 2 ]
    • [ -d "$1" ] && [ $# -eq 2 ]
    • [ -f "$1" ] && [ $# -eq 2 ]
    Show the answer

    [ -f "$1" ] && [ $# -eq 2 ]

    Two conditions to satisfy together are joined by &&; || would accept one without the other. -f checks the regular file (-d would require a directory) and -eq 2 asks for exactly two arguments, where -ge 2 would accept three.