Menu
CoddyTech

Script Arguments

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

A script often needs input it cannot know in advance: a file name, a user, a number. You pass that input as arguments, the words you type after the script's name. Inside the script, $1 holds the first argument, $2 the second, and so on. $0 holds the name the script was started with.

#!/bin/bash
echo "Copying $1 to $2"
echo "Started as $0"

Run it with two arguments:

bash copy.sh notes.txt backup.txt

It prints Copying notes.txt to backup.txt, then Started as copy.sh. Running a script with bash in front works without chmod +x. An argument you leave out expands to an empty string.

Quote an argument that contains spaces: bash copy.sh "my notes.txt" backup.txt makes $1 the whole name my notes.txt.

challenge icon

Challenge

Easy

Write a greeting script that takes a name and a city.

  1. Open greet.sh from the file tree. It already starts with the shebang line.
  2. Below the comment, add one echo line that prints Hello, NAME! Welcome to CITY. where NAME is the first argument and CITY is the second.
  3. Save the file.

Try it: run bash greet.sh Ana Lisbon. It prints:

Hello, Ana! Welcome to Lisbon.

Then run bash greet.sh Sam Oslo: the greeting changes to Hello, Sam! Welcome to Oslo.

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