AI Hints
Home›Linux Tutorial›Loops and Functions
Linux · Lesson 107 of 120

Functions

Name a block of commands.

⏱ 2 min read▶ Video at 2:23:16🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

As scripts grow, you'll repeat the same few lines in several places. A function gives those lines a name. Then you just call the name, as many times as you like.

Functions
From the video: Functions
  • Scripts grow
  • Repeated lines
  • Give them a name

welcome.sh

A function is a name, empty brackets, and the commands inside curly braces. Greet uses dollar one, its own first argument. Line just prints a divider. Below the functions, we call them by name, like normal commands.

nano welcome.shbash
#!/bin/bash
greet() {
  echo "Hello, $1! Welcome aboard."
}

line() {
  echo "--------------------"
}

line
greet Priya
greet Alex
line

Calling functions

The divider, two greetings, and the divider again. Each function was written once, and used many times. If we change the divider, it changes everywhere.

Terminal
./welcome.sh
--------------------
Hello, Priya! Welcome aboard.
Hello, Alex! Welcome aboard.
--------------------

Function tips

Define functions before you use them, usually at the top of the script. Give them names that say what they do, like make backup, or check disk. Use local for variables that belong only inside the function. And return a number, to report success or failure.

keyvalue
name() { … }define it
name arg1 arg2call it
$1 insidethe function's argument
local x=1a private variable

Summary

Functions name a block of commands, so you can reuse it. Define them at the top, and call them by name, with arguments. Next, making scripts stop safely when something fails.

Key takeaways
  • name() { … }
  • name arg
  • local
Next up: Safer Scripts — set -e and bash -x