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.txtIt 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
EasyWrite a greeting script that takes a name and a city.
- Open
greet.shfrom the file tree. It already starts with the shebang line. - Below the comment, add one
echoline that printsHello, NAME! Welcome to CITY.where NAME is the first argument and CITY is the second. - 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
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