0
0
Bash-scriptingConceptBeginner · 3 min read

What is $0 $1 $2 in Bash: Understanding Positional Parameters

In Bash, $0 is the name of the script being run, while $1 and $2 are the first and second arguments passed to the script respectively. These are called positional parameters and let you access input values given when running the script.
⚙️

How It Works

When you run a Bash script, you can give it extra information called arguments. Think of these arguments like items you hand to a friend to do a task. Inside the script, $0 is like the friend’s name tag—it tells you the script's own name. The $1, $2, and so on are like the items your friend received, in order.

This means $1 holds the first argument, $2 the second, and so forth. If you imagine a recipe, $0 is the recipe name, and $1, $2 are ingredients you add when cooking.

💻

Example

This example script prints the script name and the first two arguments it receives.

bash
#!/bin/bash

echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
Output
Script name: ./example.sh First argument: hello Second argument: world
🎯

When to Use

Use $0, $1, $2, etc., when you want your Bash script to work with inputs given by the user or another program. For example, if you write a script to rename files, you might pass the old and new file names as arguments.

This makes your scripts flexible and reusable because they can handle different inputs without changing the code. It’s common in automation, installation scripts, and command-line tools.

Key Points

  • $0 is the script’s own name or path.
  • $1, $2, etc., are the arguments passed to the script.
  • Arguments are accessed in order, starting at 1.
  • Use these to make scripts dynamic and accept user input.

Key Takeaways

$0 holds the script name; $1 and $2 hold the first and second arguments.
Positional parameters let scripts access input values given when running them.
Use these to make your Bash scripts flexible and interactive.
Arguments are counted starting from 1; $0 is special as the script name.