0
0
Bash Scriptingscripting~3 mins

Why Command-line arguments ($1, $2, ...) in Bash Scripting? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could run the same script on any file without opening it to change a single line?

The Scenario

Imagine you have a script that needs to process different files every time you run it. Without command-line arguments, you must open the script and change the file name inside the code manually before each run.

The Problem

This manual method is slow and frustrating. You risk making mistakes by editing the script repeatedly. It also wastes time and makes automation impossible because you can't easily tell the script which file to use when running it.

The Solution

Command-line arguments let you pass information directly to your script when you run it. Instead of changing the script, you just type the file name after the script's name. The script reads these inputs as variables like $1, $2, and uses them automatically.

Before vs After
Before
filename="data.txt"
echo "Processing $filename"
After
echo "Processing $1"
What It Enables

This makes your scripts flexible and reusable, letting you run the same script on many inputs without changing the code.

Real Life Example

For example, a backup script can take the folder name as an argument, so you can back up different folders just by typing: ./backup.sh Documents or ./backup.sh Pictures.

Key Takeaways

Manual editing of scripts for each input is slow and error-prone.

Command-line arguments let you pass inputs easily when running scripts.

This makes scripts flexible, reusable, and ready for automation.