Passing Arguments to Functions

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 89 of 205

A function becomes much more useful when it can work on different data each time it is called. In Bash you pass data to a function the same way you pass it to a command: you write the values after the function name, separated by spaces. Inside the function, those values are available as positional parameters: $1, $2, $3 and so on.

There is no parameter list in the definition. The parentheses in name() { ... } always stay empty. The function decides inside its body how many arguments it expects and what they mean.

Basic Example

greet() {
    echo "Hello, $1! You are number $2."
}

greet Ana 7

Output:

Hello, Ana! You are number 7.

The call greet Ana 7 gives the function two arguments. Inside the body, $1 is Ana and $2 is 7. The command-line parameters from lesson 42 work in exactly the same way, with the function's arguments in place of the script's arguments.

The Special Parameters in a Function

All the special parameters of lesson 43 are available inside a function:

ParameterMeaning inside a function
$1, $2, ...The first, second, ... argument
${10}The tenth argument (braces are required from 10 on)
$#The number of arguments
$@All arguments, as separate words
$*All arguments, as one word when quoted
$0The name of the script, not of the function
show() {
    echo "count: $#"
    echo "first: $1"
    echo "all:   $*"
}
show red green blue
show
count: 3
first: red
all:   red green blue
count: 0
first: 
all:   

When the function is called without arguments, $# is 0, and $1 and $* are empty strings. Bash does not report an error for a missing argument unless you ask for one (see below). The name of the function itself is not in $0: Bash leaves $0 as the script name, and the function name is available as ${FUNCNAME[0]} (lesson 88).

The tenth argument needs braces, because $10 is read as $1 followed by the character 0:

tenth() { echo "10th with braces: ${10}; without: $10"; }
tenth 1 2 3 4 5 6 7 8 9 ten
10th with braces: ten; without: 10

Quoting Arguments with Spaces

The shell splits a command line into words before the function runs. The function receives the words, not the original line. To pass a value that contains spaces as one argument, quote it (lessons 46 and 55):

count_args() { echo "$# arguments"; }
count_args one two three
count_args "one two" three
count_args "one two three"
name="Ana Maria"
count_args $name
count_args "$name"
3 arguments
2 arguments
1 arguments
2 arguments
1 arguments

The unquoted $name was split into two words by word splitting (lesson 53), so the function saw two arguments. The quoted "$name" stays one argument. Quote variables at the call site the same way you quote them everywhere else.

Using All the Arguments: "$@" and "$*"

To process every argument, loop over "$@". The quotes matter. With them, each argument stays one item, even when it contains spaces:

show_each() { for a in "$@"; do echo "[$a]"; done; }
show_each "a b" c
[a b]
[c]

The other forms behave differently when given the same arguments "a b" and c:

star_each()  { for a in $*;   do echo "[$a]"; done; }
qstar_each() { for a in "$*"; do echo "[$a]"; done; }
star_each "a b" c
qstar_each "a b" c
[a]
[b]
[c]
[a b c]

An unquoted $* (or $@) is split again into words, so "a b" falls apart into a and b. A quoted "$*" joins everything into one string. Only the quoted "$@" keeps the original arguments intact. Use "$@" almost always, and "$*" only when you want one string, for example in a log message.

When there are no arguments, "$@" expands to nothing, so the loop runs zero times. An empty argument is still an argument:

none() { echo "args: $#"; for a in "$@"; do echo "loop ran"; done; }
none
none ""
args: 0
args: 1
loop ran

Function Arguments Hide the Script Arguments

A script has its own positional parameters (the arguments of the command line). While a function runs, $1, $2 and the others refer to the function's arguments. When the function returns, the script's parameters come back:

show_args() { echo "inside function: 1=[$1] 2=[$2] count=$#"; }
echo "script: 1=[$1] 2=[$2] count=$#"
show_args x y z
echo "script again: 1=[$1] 2=[$2] count=$#"

Run with bash scope89.sh first second:

script: 1=[first] 2=[second] count=2
inside function: 1=[x] 2=[y] count=3
script again: 1=[first] 2=[second] count=2

If a function needs the script's arguments, you must pass them on explicitly. The usual way is to hand over all of them with "$@":

main() { echo "main got $# args: $*"; }
main "$@"

Run with bash pass89.sh "a b" c d:

main got 3 args: a b c d

The script received three arguments (a b, c, d), and main received the same three, because "$@" preserved the grouping. This main "$@" pattern is common at the end of well-structured scripts (lesson 94).

Checking the Number of Arguments

A function should check that it has what it needs. The test $# (lesson 73) counts the arguments:

add() {
    if [ "$#" -ne 2 ]; then
        echo "usage: add NUMBER NUMBER" >&2
        return 2
    fi
    echo $(( $1 + $2 ))
}
add 3 4
add 3; echo "status $?"
7
usage: add NUMBER NUMBER
status 2

The usage message goes to standard error (lesson 59), and return 2 reports the problem to the caller (lesson 90). Status 2 is the usual choice for wrong usage.

Default Values and Required Arguments

The parameter expansions from lesson 45 work on $1 and the other parameters:

hello() {
    local who=${1:-World}
    echo "Hello, $who"
}
hello
hello Ana
Hello, World
Hello, Ana

${1:-World} uses World when $1 is unset or empty. The local keyword (lesson 92) keeps who inside the function.

To make an argument required, use ${1:?message}. When the argument is missing, Bash prints the message, and a non-interactive shell stops with status 1. The example below runs the call in a subshell, so only the subshell stops:

need_one() {
    local f=${1:?need a file name}
    echo "using $f"
}
( need_one ); echo "subshell status $?"
bash: 1: need a file name
subshell status 1

The test run printed a script name and line number in front of the message (for example t89b.sh: line 2:); an interactive shell prints bash:. Without the subshell parentheses, the whole script ended at the failed call (the line echo "after call" after it was never run, and the status was 1), so use this form only when stopping the script is the intended reaction.

Checking the Value of an Argument

Arguments are always text. Bash has no numeric or boolean types, so the function must check that the text means what it expects. A regular-expression test with [[ ]] (lesson 69) works well for integers:

is_number() { [[ $1 =~ ^-?[0-9]+$ ]]; }
for v in 42 -7 3.5 abc ""; do
    if is_number "$v"; then
        echo "[$v] is an integer"
    else
        echo "[$v] is not an integer"
    fi
done
[42] is an integer
[-7] is an integer
[3.5] is not an integer
[abc] is not an integer
[] is not an integer

The function body is only a test, so its exit status is the result. Callers can use it directly in an if (lesson 90). Without such a check, a text argument like abc would be read as a variable name inside $(( )) and silently counted as 0 (lesson 73).

Handling Any Number of Arguments

A loop over "$@" handles lists of any length:

total() {
    local sum=0 n
    for n in "$@"; do
        sum=$((sum + n))
    done
    echo "sum of $# numbers: $sum"
}
total 5 10 15
total
sum of 3 numbers: 30
sum of 0 numbers: 0

With no arguments, the loop does not run and the sum stays 0.

Separating the First Argument with shift

The shift command (lesson 44) removes $1 and moves the others down by one. It is perfect when the first argument has a special meaning and the rest form a list:

log() {
    local level=$1
    shift
    echo "[$level] $*"
}
log INFO server started on port 8080
log WARN disk almost full
[INFO] server started on port 8080
[WARN] disk almost full

After shift, $* holds everything except the level. A shift inside a function changes only the function's own parameters, never the script's.

The same is true for set --, which replaces all the positional parameters:

reset_args() { set -- new1 new2; echo "inside: $* ($#)"; }
set -- keep1 keep2 keep3
reset_args original
echo "outside: $* ($#)"
inside: new1 new2 (2)
outside: keep1 keep2 keep3 (3)

Passing an Array

You cannot pass an array as one value, but you can pass its elements as separate arguments with "${array[@]}" (lesson 104 shows more ways):

files=("my file.txt" "b.txt" "c.txt")
list() { printf '%s\n' "$@"; }
list "${files[@]}"
cnt() { echo $#; }
cnt "${files[@]}"
cnt ${files[@]}
my file.txt
b.txt
c.txt
3
4

The quoted form passes three arguments, and my file.txt stays whole. The unquoted ${files[@]} is split at the space, so the function receives four arguments. This is the same word-splitting problem as before, and the cure is the same: quote it.

Parsing Options Inside a Function

A function can accept options like a command does. The loop below reads options until it meets the first argument that is not an option, using case (lesson 75) and shift:

backup() {
    local verbose=0 dest=/tmp
    while (( $# > 0 )); do
        case $1 in
            -v) verbose=1; shift ;;
            -d) dest=$2; shift 2 ;;
            --) shift; break ;;
            -*) echo "unknown option: $1" >&2; return 1 ;;
            *)  break ;;
        esac
    done
    echo "verbose=$verbose dest=$dest files: $*"
}
backup -v -d /backups a.txt b.txt
backup a.txt
backup -x a.txt; echo "status $?"
backup -- -weird-name.txt
verbose=1 dest=/backups files: a.txt b.txt
verbose=0 dest=/tmp files: a.txt
unknown option: -x
status 1
verbose=0 dest=/tmp files: -weird-name.txt

The loop runs while arguments remain. -v sets a flag and shifts by one, -d takes the next word as its value and shifts by two, and -- ends the option list, which allows a file name that starts with a dash. The getopts command (lesson 130) is a ready-made tool for the same job, and lessons 127 to 133 cover argument parsing in depth.

Portability

Passing and reading arguments with $1, $#, "$@" and shift is POSIX and works in Dash. A test of $#, $*, a "b c" d and ${10} gave the expected results in Dash. The local keyword used in several examples is not part of the POSIX standard, even though Dash accepts it. The array and [[ =~ ]] examples need Bash.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Passing Arguments to Functions and get answers drawn from it.

Signed-in readers only.