AI Hints
Home›Linux Tutorial›Your First Scripts
Linux · Lesson 101 of 120

Script Arguments

$1, $2 and $#.

⏱ 2 min read▶ Video at 2:15:31🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Commands like CP take arguments. What to copy, and where. Your scripts can take arguments too, so the same script works with different files, names, or folders.

Script Arguments
From the video: Script Arguments
  • cp takes arguments
  • Scripts can too
  • One script, many uses

greet.sh

Inside a script, dollar one is the first argument, and dollar two is the second. Here we store them in friendlier variables, name, and city. Dollar hash is the number of arguments given.

nano greet.shbash
#!/bin/bash
name="$1"
city="$2"
echo "Hi $name from $city!"
echo "You gave me $# arguments."

Passing arguments

Run it with Priya and Leeds, and they fill in dollar one and dollar two. Notice the quotes around New York. Without them, New and York would be two separate arguments. With quotes, it's one.

Terminal
./greet.sh Priya Leeds
Hi Priya from Leeds!
You gave me 2 arguments.
./greet.sh Jo "New York"
Hi Jo from New York!
You gave me 2 arguments.

Special variables

Bash gives every script a few special variables. Dollar zero is the script's own name. Dollar one to dollar nine are the arguments. Dollar hash counts them. And dollar at means all of them, which is handy in loops. Always wrap them in double quotes, in case they contain spaces.

VariableMeans
$0the script's name
$1, $2 …the arguments
$#how many arguments
"$@"all the arguments

Summary

Dollar one, dollar two, and so on are a script's arguments, and dollar hash counts them. Quote them, to keep spaces safe. Next, asking the user questions.

Key takeaways
  • $1 $2
  • $#
  • "$@"
Next up: Reading Input — read -p