0
0
Bash Scriptingscripting~3 mins

Why Function arguments ($1, $2 inside function) in Bash Scripting? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one function that works for any input without changing its code?

The Scenario

Imagine you have a bash script with a function that needs to work with different file names or user inputs each time you run it. Without function arguments, you have to edit the function code every time to change these values.

The Problem

Manually changing values inside the function is slow and error-prone. You might forget to update all places or introduce typos. It also makes your script rigid and hard to reuse for different inputs.

The Solution

Using function arguments like $1, $2 inside a bash function lets you pass different values each time you call it. This makes your function flexible, reusable, and your script easier to maintain.

Before vs After
Before
myfunc() {
  echo "Processing file.txt"
}
myfunc
After
myfunc() {
  echo "Processing $1"
}
myfunc file.txt
What It Enables

You can write one function that works with any input, making your scripts powerful and adaptable.

Real Life Example

Suppose you want to compress different files using the same function. Passing the file name as an argument lets you compress any file without rewriting the function.

Key Takeaways

Function arguments let you pass data into functions dynamically.

This avoids hardcoding values and makes scripts reusable.

Using $1, $2 inside functions is simple but powerful.