Shell Script · Function Arguments

Shell Scripting · Lesson 15

Function Arguments

Pass arguments to shell functions. Access parameters inside function. Build dynamic reusable code. Real automation examples.

What Are Function Arguments?

Function arguments allow you to pass values into a function when calling it. These values can then be used inside the function using positional parameters.

Why Use Function Arguments?

Reusability

Write one function and reuse it with different values.

Flexibility

Change behavior without changing code.

Dynamic Inputs

Pass runtime values into functions.

Positional Parameters

  • $1 – First argument
  • $2 – Second argument
  • $# – Total number of arguments
  • $@ – All arguments (as list)
  • $* – All arguments as a single string

Function Argument Examples

1. Basic Function Arguments

Arguments passed to a function are accessed using $1, $2, etc.

terminal — bash
function-args
greet() {
echo "Hello $1"
}
 
greet John

2. Multiple Arguments

You can pass multiple arguments to a function.

terminal — bash
function-args
add() {
sum=$(( $1 + $2 ))
echo "Sum: $sum"
}
 
add 10 20

3. Special Parameters

Special variables like $#, $@, and $* provide argument info.

terminal — bash
function-args
show_args() {
echo "Total arguments: $#"
echo "All arguments: $@"
}
 
show_args one two three

4. Using shift Command

Shift moves positional parameters to the left.

terminal — bash
function-args
print_args() {
while [ "$#" -gt 0 ]; do
echo "Argument: $1"
shift
done
}
 
print_args A B C

Best Practices

Best Practices

  • Always validate arguments before using them.
  • Use meaningful function and variable names.
  • Use shift for processing multiple arguments.
  • Document expected arguments in comments.

Practice Task – Function Arguments

  • Create a function that adds two numbers.
  • Create a function that prints all arguments.
  • Create a function that counts arguments.

Next lesson: Script Arguments ($0, $1, $@)