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"
donebash 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
EasyWrite a trip planner that takes a traveller's name and then any number of stops.
- Open
trip.sh. It already starts with the shebang line. - Save the first argument in a variable called
name, then remove it from the list withshift. - Print
Stops for NAME: N, where N is the number of stops left. - Loop over the remaining arguments and print
Stop: CITYfor each one, in the order given. - 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: TokyoThen run bash trip.sh Sam: with no stops, it prints only Stops for Sam: 0.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground