0
0
Bash Scriptingscripting~5 mins

Why functions organize reusable code in Bash Scripting

Choose your learning style9 modes available
Introduction
Functions help you keep your code neat and easy to use again without rewriting it.
When you need to repeat the same steps multiple times in a script.
When you want to make your script easier to read and understand.
When you want to fix or update a task in one place instead of many.
When you want to share a piece of code with others or use it in different scripts.
Syntax
Bash Scripting
function_name() {
  commands
}

# To run the function:
function_name
Functions group commands under one name you can call anytime.
Use parentheses () after the function name, then curly braces {} for the commands.
Examples
This function prints a greeting message when called.
Bash Scripting
greet() {
  echo "Hello, friend!"
}

greet
This function adds two numbers given as inputs and prints the result.
Bash Scripting
add() {
  echo $(( $1 + $2 ))
}

add 3 5
Sample Program
This script defines a function that prints a greeting. It calls the function twice to show reuse.
Bash Scripting
#!/bin/bash

say_hello() {
  echo "Hi there!"
}

say_hello
say_hello
OutputSuccess
Important Notes
Functions make your scripts shorter and easier to fix.
You can pass information to functions using arguments like $1, $2, etc.
Always define functions before you call them in your script.
Summary
Functions let you reuse code without copying it again and again.
They make scripts easier to read and update.
Use functions to organize tasks inside your scripts.