0
0
Bash Scriptingscripting~5 mins

Function arguments ($1, $2 inside function) in Bash Scripting

Choose your learning style9 modes available
Introduction
Functions can take inputs to work with different data each time. Using $1, $2 inside a function lets you access these inputs easily.
You want to reuse a set of commands but with different values each time.
You need to pass a filename or user input to a function to process it.
You want to write a script that can handle multiple tasks by changing arguments.
You want to keep your script organized by breaking tasks into functions with inputs.
Syntax
Bash Scripting
function_name() {
  echo "First argument is $1"
  echo "Second argument is $2"
}
Inside a function, $1, $2, etc. refer to the arguments passed to that function, not the script.
You can use as many arguments as you want, accessed by $1, $2, $3, and so on.
Examples
This function greets the person whose name is passed as the first argument.
Bash Scripting
greet() {
  echo "Hello, $1!"
}
greet Alice
This function adds two numbers passed as arguments and prints the result.
Bash Scripting
add() {
  sum=$(( $1 + $2 ))
  echo "Sum is $sum"
}
add 5 7
This function prints three arguments passed to it.
Bash Scripting
show_args() {
  echo "Arg1: $1"
  echo "Arg2: $2"
  echo "Arg3: $3"
}
show_args one two three
Sample Program
This script defines a function that prints a name and age passed as arguments.
Bash Scripting
#!/bin/bash

print_info() {
  echo "Name: $1"
  echo "Age: $2"
}

print_info "John" 30
OutputSuccess
Important Notes
If you call a function without enough arguments, the missing ones will be empty strings.
You can use "$@" inside a function to access all arguments as a list.
Always quote your variables like "$1" to avoid issues with spaces or special characters.
Summary
Use $1, $2, etc. inside functions to access the inputs given when calling the function.
Functions help reuse code with different data by passing arguments.
Remember that $1 inside a function is different from $1 in the main script.