Bash Functions

Bash Functions let you group a set of Bash commands under one reusable name. In this Bash Tutorial, we shall learn how to define Bash functions, call them, pass arguments, use local variables, return status codes, and avoid common function mistakes in shell scripts.

What Bash functions are used for in shell scripts

A Bash function is useful when the same logic is needed more than once in a script. Instead of repeating commands, you define the function once and call it wherever required. This makes scripts easier to read, test, and maintain.

  • Function has to be defined in the shell script first, before you can use it.
  • Arguments could be passed to functions and accessed inside the function as $1, $2 etc.
  • Local Variables could be declared inside the function and the scope of such local variables is only that function.
  • Using functions, you may override builtin commands of Bash Shell.

Functions are commonly used for validation, printing formatted messages, reading configuration values, wrapping repeated commands, handling errors, and organizing long scripts into smaller sections.

Bash function syntax using function keyword and parentheses

Any of the following two syntax could be used for defining a function in bash shell scripting.

</>
Copy
function <function_name> {
	# function body
}
</>
Copy
<function_name>() {
	# function body
}
<function_name>Name of the function. Any word consisting only of alphanumeric characters and under?scores, and beginning with an alphabetic character or an under?score, can be used as a function name.

The name() style is widely used in portable Bash scripts. The function name style is also supported by Bash, but avoid mixing both styles in the same script unless there is a clear reason.

Bash function naming rules and calling rules

A function name should be clear and should describe the action performed by the function, such as print_usage, backup_file, or check_user_input. To call a Bash function, write only the function name followed by its arguments. Do not use parentheses while calling it.

</>
Copy
function_name argument1 argument2

The following call is a common mistake because Bash does not call functions like many programming languages do.

</>
Copy
function_name(argument1, argument2)   # not valid Bash function call syntax

Bash function example with a simple reusable command block

In the following example, we will create a function named sampleFunction, and call it.

Bash Script File

</>
Copy
#!/bin/bash

# bash function example
sampleFunction () {
	echo Hello from Sample Function.
}

sampleFunction

Output

~$ ./bash-function 
Hello from Sample Function.

The function is defined before the call. When sampleFunction is executed, Bash runs the commands inside the function body.

Bash function example using the function keyword

In this example, we will use function keyword to define a function.

Bash Script File

</>
Copy
#!/bin/bash

# bash function example
function sampleFunction {
	echo This is another way to define function in bash scripting.
}

sampleFunction

Output

~$ ./bash-function-2 
This is another way to define function in bash scripting.

This form works in Bash and is easy to read for beginners. In team scripts, choose one function declaration style and use it consistently.

Bash function with arguments using $1, $2, $3

In this example, we shall learn to pass arguments to functions, and access the arguments inside the function.

Bash Script File

</>
Copy
#!/bin/bash

# bash function example with arguments
function functionWithArgs {
	echo $1 : $2 in this $3
}

functionWithArgs "`date +"[%m-%d %H:%M:%S]"`" "Learn Functions" "Bash Tutorial" 

Output

$ ./bash-function-arguments 
[11-21 19:30:21] : Learn Functions in this Bash Tutorial

Inside a function, positional parameters work like script arguments. $1 is the first function argument, $2 is the second argument, and so on. The script’s own positional parameters are temporarily replaced while the function is running.

Reading all Bash function arguments with $@ and argument count with $#

Use $# to get the number of arguments passed to a Bash function. Use "$@" when you need to loop through all arguments safely while preserving spaces in each argument.

</>
Copy
#!/bin/bash

print_items() {
	echo "Total items: $#"

	for item in "$@"
	do
		echo "- $item"
	done
}

print_items "Linux" "Bash functions" "Shell scripting"

Output

Total items: 3
- Linux
- Bash functions
- Shell scripting

Prefer "$@" over unquoted $* in most scripts. Quoting helps prevent word-splitting problems when an argument contains spaces.

Using local variables inside Bash functions

By default, variables in Bash are global within the script. If a function should use a variable only inside its own body, declare it with local. This prevents accidental changes to variables used elsewhere in the script.

</>
Copy
#!/bin/bash

message="Outside function"

show_message() {
	local message="Inside function"
	echo "$message"
}

show_message
echo "$message"

Output

Inside function
Outside function

In this example, the function has its own message variable. The original message value outside the function is not changed.

Returning status from a Bash function with return

A Bash function does not return text like a function in many general-purpose programming languages. The return command returns an exit status, where 0 usually means success and a non-zero value usually means failure. To produce text, print it with echo or printf and capture it if needed.

</>
Copy
#!/bin/bash

check_file() {
	local file_path="$1"

	if [[ -f "$file_path" ]]
	then
		return 0
	else
		return 1
	fi
}

if check_file "report.txt"
then
	echo "File exists"
else
	echo "File does not exist"
fi

The if statement checks the function’s exit status. This pattern is useful for validation functions such as check_file, is_number, or has_permission.

Capturing output from a Bash function with command substitution

When a Bash function needs to provide a string value, print the value and capture it using command substitution. Use printf when you need predictable formatting.

</>
Copy
#!/bin/bash

make_filename() {
	local name="$1"
	printf "%s_backup.tar.gz" "$name"
}

backup_name=$(make_filename "project")
echo "$backup_name"

Output

project_backup.tar.gz

Do not use return for strings. Use return for status codes and printed output for values.

Bash function mistakes that cause script errors

The following mistakes are common when writing Bash functions for the first time.

  • Calling a function before it is defined: Bash reads and executes scripts from top to bottom, so define the function before calling it.
  • Using parentheses while calling: Use print_message "Hello", not print_message("Hello").
  • Forgetting quotes around arguments: Use "$@" and "$1" when arguments may contain spaces.
  • Expecting return to send text: return sends only a numeric status code.
  • Changing global variables accidentally: Use local for temporary variables inside functions.
  • Overriding important command names: Avoid naming functions test, cd, echo, or other common command names unless you intentionally want to override behavior.

If you intentionally define a function with the same name as a command, you can use the command builtin to call the original external or builtin command when appropriate.

</>
Copy
command echo "Call the original echo command"

Bash functions QA checklist for tutorial scripts

  • The function is defined before the first call in the script.
  • The function name describes the task and does not accidentally shadow a common command.
  • Arguments are read with $1, $2, $#, or quoted "$@" as needed.
  • Temporary variables inside the function use local.
  • The function uses return only for numeric status codes.
  • String output from the function is printed with echo or printf.
  • Arguments and variables are quoted when they may contain spaces or special characters.
  • Examples include both the script and the expected output where output helps the reader verify the result.

Bash functions FAQs

Can a Bash function be called before it is defined?

No. In a normal Bash script, the function must be defined before the line where it is called. Bash executes the script from top to bottom.

How are arguments passed to a Bash function?

Arguments are written after the function name during the call. Inside the function, they are available as $1, $2, $3, and so on. The count is available in $#, and all arguments can be read with "$@".

What is the difference between return and echo in a Bash function?

return sets the function’s numeric exit status. echo prints text. Use return for success or failure and use echo or printf when the function needs to output a value.

Should variables inside a Bash function be local?

Use local for variables that are needed only inside the function. This reduces accidental changes to other variables in the script.

Which Bash function syntax should I use?

Both name() { ...; } and function name { ...; } work in Bash. The name() form is commonly used in shell scripts. The most important rule is to use one style consistently.

Bash functions reference links

Bash functions summary

In this Bash Tutorial, we have learned about Bash Functions, how to define them, how to call them, how to pass arguments, how to use local variables, and how to return a status from a function. Functions are a practical way to keep Bash scripts organized when the same command logic is used more than once.