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

Function Basics

A function is like a recipe card you write once and use again and again. You give it a name, and every time you say that name the computer follows the steps.

In this page:

  1. Function Basics
Syntax
bash
function_name() {
  commands
}
function_name

Function Basics

A Bash function groups commands under a name using function_name() { ... }, letting you call the same logic repeatedly without duplicating code.

Functions must be defined before they are called in the script. They're invoked just like any other command, by writing their name.

Note: The function keyword before the name is optional in Bash — greet() { ... } and function greet { ... } both work.

Example: Function Basics

bash
#!/bin/bash
greet() {
    echo "Hello from a function!"
}

greet
greet
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. Writing greet() { ... } and then calling it as greet(), when it is called with just greet.
  2. Calling a function before its definition.
  3. Redefining a function with the same name as an existing command, which hides that command in the script.

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.