0
0
Bash Scriptingscripting~5 mins

Function definition in Bash Scripting

Choose your learning style9 modes available
Introduction
Functions let you group commands together to reuse them easily and keep your script organized.
When you want to run the same set of commands multiple times without rewriting them.
When you want to break a big script into smaller, easy-to-understand parts.
When you want to make your script cleaner and easier to maintain.
When you want to pass information to a group of commands and get results back.
Syntax
Bash Scripting
function_name() {
  commands
}

# or

function function_name() {
  commands
}
Function names should be simple and descriptive.
Use parentheses () after the function name, but no parameters go there in bash.
Examples
A simple function named greet that prints a message.
Bash Scripting
greet() {
  echo "Hello, friend!"
}
Another way to define a function with parentheses.
Bash Scripting
function say_goodbye() {
  echo "Goodbye!"
}
Function that runs the date command to show current date and time.
Bash Scripting
print_date() {
  date
}
Sample Program
This script defines a function say_hello that prints a welcome message. Then it calls the function to show the message.
Bash Scripting
#!/bin/bash

say_hello() {
  echo "Hello, welcome to the script!"
}

say_hello
OutputSuccess
Important Notes
Always call the function by its name followed by parentheses or just the name in bash.
Functions help avoid repeating code and make scripts easier to read.
You can pass arguments to functions using $1, $2, etc., inside the function.
Summary
Functions group commands to reuse them easily.
Define functions with function_name() { commands } or function function_name() { commands }.
Call functions by their name to run the grouped commands.