Bash: functions and arrays

Declaring and calling a function, variable scope with local, return versus echo, indexed and associative arrays and reading options with getopts: predicting what a script prints.

  • 32 cards
  • 5 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
  5. Understand

A few cards from the deck

  • Bash function: what is it?

    Show the answer

    A named group of commands, declared with name() { … }, which receives its arguments in $1, $2, $# and $@ and is called like a command.

    The function's parameters hide the script's own for the length of the call: $1 inside the function is not the script's $1.

  • What does this script print?

    ```bash
    f() { local x=2; y=3; }
    x=1; y=1
    f
    echo $x $y
    `

    • 1 3
    • 2 3
    • 1 1
    • 2 1
    Show the answer

    1 3

    x is local: the call does not touch the script's x, which stays at 1. y is assigned without local, so it is global: it becomes 3.

  • In a Bash function, the … keyword limits a variable to the length of the call; without it, the assignment is ….

    Show the answer

    In a Bash function, the local keyword limits a variable to the length of the call; without it, the assignment is global.

    f() { local x=2; y=3; }: after the call, x keeps its earlier value and y is 3.

  • Local variable: what is it?

    Show the answer

    A variable declared with local inside a function: it exists only during the call and leaves a variable of the same name elsewhere alone.

    Without local, every assignment inside a function is global: it overwrites the calling script's variable, for instance a loop counter i.

  • A function that was supposed to hand back a file name ends with return $name. Running it prints return: rapport.txt: numeric argument required. Which fix is right?

    • Write return "$name" in double quotes
    • Write echo "$name" and capture it with f=$(file_name)
    • Declare the variable name with local before the return
    • Write return 0 instead, then read $?
    Show the answer

    Write echo "$name" and capture it with f=$(file_name)

    return only accepts a number: quotes change nothing, nor does local. return 0 would lose the name. The function's output is the right channel for a text.