>_ IzzyLab

Hands-on task

This task is step 4 of the course “Your first bash script”

Script arguments: $1 and $#

easy~6 min

Write the script /root/greet.sh. It takes a name as its first argument and prints two lines: a greeting and how many arguments it was given in total.

$ bash greet.sh Alice
Hello, Alice!
Arguments: 1

$ bash greet.sh Bob x y
Hello, Bob!
Arguments: 3

Don't write the name into the script — it must come from the argument, so the script works with any name, not just the ones in the example.

What you'll practise:
  • bash scripts
  • positional arguments
  • $1
  • $#

Topic breakdown

Like any command, a script can be given arguments — the words after its name:

bash copy-info.sh report.txt /backup

Inside the script they're available through special variables:

  • $1, $2, $3 … — the first, second, third argument;
  • $# — how many arguments were passed;
  • $0 — the name of the script itself.

For example, copy-info.sh:

#!/bin/bash
echo "Copying: $1"
echo "To: $2"
echo "Arguments in total: $#"

For the run above it answers Copying: report.txt, To: /backup and Arguments in total: 2. If an argument is missing, $2 is just an empty string — there's no error.

As with ordinary variables, expansion works in double quotes and doesn't work in single quotes.

What's checked

  1. /root/greet.sh created
  2. The greeting takes the name from the first argument
  3. The second line shows the number of arguments
  4. The script prints exactly two lines

What it looks like