Function
The function is the set of commands that can be called multiple times. It is used to avoid writing the same block of code again and again.
Syntax:
function_name () { commands } OR function function_name { commands }
Both the format of writing functions is correct in bash scripting.
Example 1: Creating local variable
The local variable is declared by using the keyword before the variable name
#!/bin/bash function first () { local x="HelloNew" echo "Inside first function x=$x" } first echo "Outside first function x = $x"
Output:
Inside first function x=HelloNew Outside first function x =
Example 2: Creating Global Variable
#!/bin/bash function first () { x="Hello Geek" echo "Inside first function x= $x" } first echo "Outside first function x = $x"
Output:
Inside first function x=Hello Geek Outside first function x = Hello Geek
Example 3: Multiple local and global variable in a program
#!/bin/bash function first () { local x="Hello Geek" local y= "Enjoy" echo "Inside first function x= $x" echo "Inside first function y= $y" } x="Hello Romy" y="good to see you!" first echo "Outside first function x = $x" echo "Outside first function y= $y"
Output:
Inside first function x= Hello Geek Inside first function y= Outside first function x = Hello Romy Outside first function y= good to see you!
Batch Script – Local VS Global Variables
In this article, we will see the differences between local and global variables in bash scripting.
Variable: The name given to a memory location that is used to store values in a program is called variables. It stores information that can be called and manipulated wherever needed in the program.
Scope: The part or extent of the program where the variable is accessible or said to be alive.
Based on the scope of the variable, it is of two types:
Local variable: those variables whose scope is within the function where it is declared( can be accessed within the declared block or function in the program)
Global variable: these variables can be accessed globally in the entire program.