← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 3 of 13

Function Arguments

Function arguments are like the ingredients you hand to a recipe. Inside the function you refer to the first, second and third thing you were given by number.

In this page:

  1. Function Arguments
Syntax
bash
function_name() {
  echo "$1" "$2"    # arguments
  echo "$#"         # argument count
}
function_name arg1 arg2

Function Arguments

Functions receive arguments the same way scripts do: $1, $2, etc. for individual arguments, $# for the count, and $@ for all of them.

There's no separate parameter-declaration syntax like in other languages — arguments are simply read positionally inside the function body. Function-local $1 shadows the script's own $1 while the function is running.

Note: Inside a function, $1 refers to the function's own first argument, not the script's.

Example: Function Arguments

bash
#!/bin/bash
greet() {
    echo "Hello, $1! You are $2 years old."
}

greet "Alice" 30
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using $1 and expecting names, when arguments are positional.
  2. Forgetting quotes around "$@", so arguments with spaces are split.
  3. Expecting $0 inside a function to be the function name.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.