0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Pass Arguments to Function in Bash: Simple Guide

In Bash, you pass arguments to a function by listing them after the function name when calling it, like my_function arg1 arg2. Inside the function, use $1, $2, etc., to access these arguments in order.
📐

Syntax

To pass arguments to a Bash function, call the function with the arguments separated by spaces. Inside the function, $1 refers to the first argument, $2 to the second, and so on. $# gives the number of arguments, and $@ represents all arguments.

bash
function_name() {
  echo "First argument: $1"
  echo "Second argument: $2"
  echo "Total arguments: $#"
}

function_name arg1 arg2
Output
First argument: arg1 Second argument: arg2 Total arguments: 2
💻

Example

This example shows a function that greets a user by name and mentions their favorite color passed as arguments.

bash
#!/bin/bash

greet() {
  echo "Hello, $1!"
  echo "Your favorite color is $2."
}

greet Alice Blue
Output
Hello, Alice! Your favorite color is Blue.
⚠️

Common Pitfalls

One common mistake is forgetting to pass arguments when calling the function, which makes $1 and others empty. Another is using $* instead of $@ when you want to handle all arguments separately. Also, quoting arguments properly is important to handle spaces.

bash
# Wrong: no arguments passed
print_args() {
  echo "Argument 1: $1"
}

print_args

# Right: pass arguments
print_args() {
  echo "Argument 1: $1"
}

print_args "Hello World"
Output
Argument 1: Argument 1: Hello World
📊

Quick Reference

  • $1, $2, ...: Access individual arguments
  • $#: Number of arguments
  • $@: All arguments as separate words
  • $*: All arguments as a single string

Key Takeaways

Pass arguments by listing them after the function name when calling it.
Use $1, $2, etc., inside the function to access each argument.
Always quote arguments to handle spaces correctly.
Use $# to get the count of arguments passed.
Use $@ to access all arguments as separate words.