3 Levels of Using Functions in Bash

Bash can be elegant too

Yang Zhou
TechToFreedom

--

Electric Tech Anime
Image from Wallhaven

Almost every developer, as long as he or she handled something relative to Linux, knows some bash commands. But it’s not necessarily everyone knows how to write and use functions properly and elegantly in bash.

In fact, if you just want to give a long command a shorter name for more convenient later reuses, you don’t need to write a function in bash. An alias is enough to give you a hand. But if you do need to encapsulate some complex logic, which may include many commands, conditions or loops, you must write a function.

This article will introduce how to write and use functions in bash and provide some essential tips in 3 levels of importance. After reading, handling functions in bash will be a piece of cake for you. 🍰

1. Define and Call a Function Correctly

Basically, there are two ways to define a function in bash: with or without the keyword function:

function func_name(){
...
}

Or omit the keyword function:

func_name(){
...
}

Tip 1: To improve the readability of your bash scripts, always add the function keyword when you are defining a new function.

--

--