Menu
CoddyTech

All The Arguments

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 2 of 39.

$1 and $2 work when you know how many arguments are coming. When you do not, two more variables help. $# holds the number of arguments, and "$@" expands to all of them, each one a separate item, so a for loop can visit them in turn.

#!/bin/bash
echo "Backing up $# files"
for f in "$@"; do
  echo "File: $f"
done

bash backup.sh notes.txt "tax 2025.pdf" prints Backing up 2 files, then File: notes.txt and File: tax 2025.pdf. The double quotes around $@ keep tax 2025.pdf one item. Without them, bash splits it at the space and the loop runs three times.

shift drops the first argument: $2 becomes $1, and $# goes down by one. Save $1 in a variable first when you still need it.

#!/bin/bash
dest=$1
shift
echo "Sending $# files to $dest"

bash send.sh backups a.txt b.txt prints Sending 2 files to backups.

challenge icon

Challenge

Easy

Write a trip planner that takes a traveller's name and then any number of stops.

  1. Open trip.sh. It already starts with the shebang line.
  2. Save the first argument in a variable called name, then remove it from the list with shift.
  3. Print Stops for NAME: N, where N is the number of stops left.
  4. Loop over the remaining arguments and print Stop: CITY for each one, in the order given.
  5. Save the file.

Try it: run bash trip.sh Ana Lisbon "New York" Tokyo. It prints:

Stops for Ana: 3
Stop: Lisbon
Stop: New York
Stop: Tokyo

Then run bash trip.sh Sam: with no stops, it prints only Stops for Sam: 0.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground