Scripts: variables and arguments

The shebang line and the execute permission, assignment without spaces, single and double quotes, command substitution and integer arithmetic, read, and the parameters $0, $1, $#, $@: reading a Bash script and predicting what it prints.

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

  • Shell variable: what is it?

    Show the answer

    A name the shell binds to a piece of text, set with name=value with no space around the = and read back with $name.

    Without the $, the shell does not read the variable: echo name prints the word name, whereas echo $name prints its value.

  • The script s.sh below is launched with ./s.sh a "b c" d. What does it print?

    ```bash
    #!/bin/bash
    echo $#
    echo "$2"
    `

    • 3 then b c
    • 4 then b c
    • 3 then b
    • 4 then b
    Show the answer

    3 then b c

    The quotes around b c make it a single argument: there are therefore three, and the second is b c.

  • To launch a script with ./s.sh, the file needs the execute permission, set with …; its … line, at the top, names the interpreter that will run it.

    Show the answer

    To launch a script with ./s.sh, the file needs the execute permission, set with chmod +x; its shebang line, at the top, names the interpreter that will run it.

    Without the execute permission, direct launching fails (Permission denied); bash s.sh still works, because the file is then merely read. A shebang pointing to a path that does not exist gives bad interpreter.

  • Positional parameter: what is it?

    Show the answer

    A value received on a script's launch line and designated by its rank: $1 for the first, $2 for the second, and so on.

    $0 is the script's own name, $# the number of values received, "$@" the list of all of them, each staying a single word.

  • A script written on Windows, launched with ./s.sh, answers bash: ./s.sh: /bin/bash^M: bad interpreter: No such file or directory, although /bin/bash exists. Which fix is needed?

    • Give the script the execute permission with chmod +x s.sh
    • Replace the first line with #!/bin/sh, which is more portable
    • Install Bash, which is missing from the /bin/bash location
    • Convert its Windows line endings to Unix line endings, with dos2unix
    Show the answer

    Convert its Windows line endings to Unix line endings, with dos2unix

    The ^M is the carriage return Windows puts at the end of each line: the system looks for an interpreter named bash followed by that character, which does not exist. Without the x permission, the message would be Permission denied, and another shebang would keep the same ^M.