0
0
Bash Scriptingscripting~5 mins

Calling functions in Bash Scripting

Choose your learning style9 modes available
Introduction
Functions let you group commands to reuse them easily. Calling a function runs those commands whenever you need.
You want to repeat a set of commands multiple times without rewriting them.
You want to organize your script into smaller, manageable parts.
You want to run a specific task inside your script when certain conditions happen.
Syntax
Bash Scripting
function_name() {
  # commands
}

function_name
Define the function first, then call it by its name.
No parentheses needed when calling the function.
Examples
Defines a function greet that prints Hello! and then calls it.
Bash Scripting
greet() {
  echo "Hello!"
}

greet
Function say_name prints the first argument passed to it.
Bash Scripting
say_name() {
  echo "My name is $1"
}

say_name Alice
Sample Program
This script defines a function say_hello that prints a greeting, then calls it.
Bash Scripting
#!/bin/bash

say_hello() {
  echo "Hello, friend!"
}

say_hello
OutputSuccess
Important Notes
Functions help avoid repeating code and make scripts cleaner.
You can pass arguments to functions like normal commands.
Always define functions before calling them in your script.
Summary
Functions group commands for reuse.
Call functions by their name without parentheses.
Functions can take arguments to work with different data.