What if you could write one function that works for any input without changing its code?
Why Function arguments ($1, $2 inside function) in Bash Scripting? - Purpose & Use Cases
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.
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.
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.
myfunc() {
echo "Processing file.txt"
}
myfuncmyfunc() {
echo "Processing $1"
}
myfunc file.txtYou can write one function that works with any input, making your scripts powerful and adaptable.
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.
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.