Course outline
Course / The terminal and the language

Read what the user supplies

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/04-02-shell-script-arguments
cd 04-02-shell-script-arguments
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Your script is started with some arguments after its name, like sh answer.sh "Mina Park" blue. Print how many arguments it received, then the first one, then every argument on its own line in the original order, keeping spaces inside an argument intact.

Example

Started as sh answer.sh "Mina Park" blue red, the script prints:

3
first=Mina Park
<Mina Park>
<blue>
<red>

The first line is the count. The second line is first= followed by the first argument. Each remaining line is one argument wrapped in < and >, so you can see exactly where each one starts and ends. "Mina Park" is one argument, even though it contains a space.

Rules

  • Edit answer.sh. It has no input files. The test starts it with at least one argument, and the arguments change between checks.
  • Print exactly these lines, in this order, using printf:
    1. the number of arguments, as a plain number
    2. first= followed directly by the first argument
    3. one line per argument, each in the form <argument>, in the order given
  • Use $# for the count, $1 for the first argument, and "$@" for the full list.
  • Put double quotes around "$@" and "$1". Without quotes, an argument with spaces is split into pieces, and an argument like * is replaced by file names.
  • printf repeats its format once for each value it is given, so one printf '<%s>\n' "$@" is enough for the last part.
  • Do not type the example values into the script. The test uses different arguments.
  • Do not print anything else, not even a blank line.

What you'll practice

$#, $1, "$@", quoting, and printf with %s.

Run it

gonomicon fetch week-1/04-02-shell-script-arguments
cd 04-02-shell-script-arguments
gonomicon test
gonomicon submit

Hints

  1. Three things to print: how many arguments there are ($#), the first one ($1), and every one separately ("$@").
  2. printf reuses its format for every extra value it is given, so printf '<%s>\n' "$@" prints one <...> line per argument. Keep the double quotes around $@ so an argument with spaces stays in one piece.
  3. Line 1: printf '%s\n' "$#". Line 2: printf 'first=%s\n' "$1". Line 3: printf '<%s>\n' "$@".

Something wrong with this lesson? Report a problem