Command-Line Arguments: $0, $1, and More

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 42 of 205

A Bash script becomes far more useful when it can receive input from the person who runs it. The words you type after the script name are called command-line arguments, and Bash hands them to the script through a set of special variables: $0 for the script name, $1, $2, $3 and so on for the arguments themselves.

How Arguments Reach a Script

When you type a command, the shell reads the whole line, splits it into words, and starts the program with those words. For a script, the first word is the script name and every word after it is an argument:

./backup.sh  notes.txt  /mnt/usb
#    ^         ^          ^
#    $0        $1         $2

Inside the script, Bash stores each word in a numbered variable. These numbered variables are called positional parameters, because their meaning depends on the position of the word in the command line.

VariableMeaning
$0The name used to run the script
$1The first argument
$2The second argument
$3 ... $9The third to the ninth argument
${10}, ${11} ...The tenth and later arguments (braces are required)
$#The number of arguments, not counting $0

A First Example

The script below prints the script name, the first three arguments and the number of arguments:

cat > args.sh <<'EOF'
#!/usr/bin/env bash
echo "script name : $0"
echo "first       : $1"
echo "second      : $2"
echo "third       : $3"
echo "count       : $#"
EOF
chmod +x args.sh
./args.sh red green
script name : ./args.sh
first       : red
second      : green
third       : 
count       : 2

Only two arguments were given, so $3 is empty. Bash does not report an error when you read an argument that was not supplied. It treats the variable like any unset variable and expands it to an empty string. The count $# is the reliable way to know how many arguments really arrived.

Run it again with four arguments:

bash args.sh red green blue yellow
script name : args.sh
first       : red
second      : green
third       : blue
count       : 4

The fourth argument, yellow, was counted by $# but not printed, because the script only prints $1 to $3.

What $0 Contains

$0 holds the script name exactly as it was typed on the command line, so it changes with the way you start the script:

CommandValue of $0
./args.sh./args.sh
bash args.shargs.sh
bash /home/ana/scripts/args.sh/home/ana/scripts/args.sh

A common use of $0 is a usage message that always shows the correct name. Because $0 can contain a whole path, remove everything up to the last slash with ${0##*/}. This expansion deletes the longest part of the value that matches */ from the front, which leaves only the file name:

cat > usage.sh <<'EOF'
#!/usr/bin/env bash
if [[ $# -lt 2 ]]; then
  echo "Usage: ${0##*/} SOURCE DEST" >&2
  exit 1
fi
echo "copy $1 to $2"
EOF
chmod +x usage.sh
./usage.sh a
echo "exit=$?"
./usage.sh a b
Usage: usage.sh SOURCE DEST
exit=1
copy a to b

The >&2 sends the usage message to standard error, where error messages belong. The script ends with exit 1 when fewer than two arguments are present, and continues normally when both are given.

Arguments Are Separated by Whitespace

Bash splits the command line on spaces. To pass a value that contains spaces as one argument, quote it:

./args.sh "New York" Paris
script name : ./args.sh
first       : New York
second      : Paris
third       : 
count       : 2

Without the quotes, the shell sees three words:

./args.sh New York Paris
script name : ./args.sh
first       : New
second      : York
third       : Paris
count       : 3

The quotes are removed by the shell. The script receives New York, not the quote characters. Lesson 46 covers single and double quotes in more detail.

To see exactly what a script receives, including empty arguments and repeated spaces, use a small helper that prints every argument between square brackets:

cat > show.sh <<'EOF'
#!/usr/bin/env bash
echo "count: $#"
for a in "$@"; do echo "[$a]"; done
EOF
chmod +x show.sh
./show.sh "New York" Paris "" 'two  spaces'
count: 4
[New York]
[Paris]
[]
[two  spaces]

An explicitly empty argument ("") is still an argument: it is counted and it keeps its position. The loop for a in "$@" is explained in the next lesson. It walks through every argument, however many there are.

Arguments Beyond the Ninth

Without braces, Bash reads only one digit after the dollar sign. So $10 means the first argument followed by the character 0. Use braces for two-digit positions:

cat > ten.sh <<'EOF'
#!/usr/bin/env bash
echo "\$10 = $10"
echo "\${10} = ${10}"
EOF
bash ten.sh a b c d e f g h i j k
$10 = a0
${10} = j

$10 expanded to a0 ($1 is a, followed by a literal 0), while ${10} correctly picked the tenth argument, j. In practice, scripts with so many arguments usually process them in a loop (see the lessons on shift and getopts later in the tutorial).

Handling Missing Arguments

Reading an argument that was not provided gives an empty string. Combine that with $# and with default values to make a script robust:

cat > noargs.sh <<'EOF'
#!/usr/bin/env bash
echo "count=$#"
echo "first=[$1]"
echo "first with default=[${1:-nobody}]"
EOF
bash noargs.sh
count=0
first=[]
first with default=[nobody]

The expansion ${1:-nobody} means "use $1, but if it is unset or empty, use nobody". Lesson 45 explains this family of expansions. Here it lets a script supply a sensible value when an argument is left out:

cat > greet.sh <<'EOF'
#!/usr/bin/env bash
name=$1
greeting=${2:-Hello}
echo "$greeting, $name!"
EOF
bash greet.sh Ana
bash greet.sh Ana Welcome
Hello, Ana!
Welcome, Ana!

The first argument is the name, and the second is an optional greeting that defaults to Hello.

A missing argument can also break arithmetic, because an empty value leaves a gap in the expression:

cat > sum.sh <<'EOF'
#!/usr/bin/env bash
echo "sum: $(( $1 + $2 ))"
EOF
bash sum.sh 4 9
bash sum.sh 4
sum: 13
sum.sh: line 2: 4 +  : syntax error: operand expected (error token is "+  ")

With only one argument, Bash evaluated 4 + and failed. Checking $# first, as usage.sh did, turns this confusing message into a clear one. Lesson 128 covers validating required arguments.

A script that expects at least one argument can also stop early with a useful message:

cat > count.sh <<'EOF'
#!/usr/bin/env bash
if [[ $# -eq 0 ]]; then
  echo "No files given" >&2
  exit 2
fi
echo "Checking $# file(s)"
for f in "$@"; do
  [[ -e $f ]] && echo "found: $f" || echo "missing: $f"
done
EOF
touch real.txt
bash count.sh
echo "exit=$?"
bash count.sh real.txt ghost.txt
No files given
exit=2
Checking 2 file(s)
found: real.txt
missing: ghost.txt

The Shell Expands Patterns Before the Script Runs

Wildcards are expanded by the shell, not by the script. The script only sees the result:

touch a.txt b.txt c.txt
./show.sh *.txt
count: 3
[a.txt]
[b.txt]
[c.txt]

The script did not receive *.txt. It received the three file names that matched. This is why a command such as rm *.txt can work on many files even though rm itself knows nothing about wildcards.

Functions Have Their Own Arguments

A function receives its own $1, $2 and $#, separate from those of the script. Inside a function, $0 still holds the script name:

cat > fn.sh <<'EOF'
#!/usr/bin/env bash
show() { echo "in function: \$0=${0##*/} \$1=$1 \$#=$#"; }
echo "script: \$1=$1 \$#=$#"
show inner1 inner2 inner3
echo "script again: \$1=$1"
EOF
bash fn.sh outer
script: $1=outer $#=1
in function: $0=fn.sh $1=inner1 $#=3
script again: $1=outer

While the function ran, $1 meant inner1. As soon as it returned, $1 meant outer again. Lessons 88 and 89 explain functions and their arguments in depth.

Arguments with bash -c

You can also run a command string with bash -c. In this form, the first word after the string becomes $0, and the rest become $1, $2 and so on:

bash -c 'echo "name=$0 first=$1 second=$2"' mytool alpha beta
name=mytool first=alpha second=beta

This catches many people by surprise: the first extra word is not $1, it is the name that the shell will use for $0 (for example in error messages).

Arguments Are Not Standard Input

Arguments and input are two different channels. Text sent through a pipe goes to standard input, and a script does not see it as an argument:

echo hi | bash args.sh | head -1
script name : args.sh

The word hi did not become $1. The script has to read standard input with commands such as read (see lesson 31) if it wants that data.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Command-Line Arguments: $0, $1, and More and get answers drawn from it.

Signed-in readers only.