Overwriting of variable
See below example:
#!/bin/bash x="Hellooooo!!" echo " Outside first function x =$x" function first () { x="Hello Geek" } first echo "After overwriting, x = $x"
Output:
Outside first function x =Hellooooo!! After overwriting, x = Hello Geek
From the example, we can see that the value of x is overwritten. To prevent the overwriting of variables we can make our variable readonly by writing ‘declare -r’ before variable declaration.
Example:
#!/bin/bash x="Hellooooo!!" echo " Outside first function x =$x" function first () { declare -r x="Hello Geek" } first echo "After overwriting, x = $x"
Output:
Outside first function x =Hellooooo!! After overwriting, x = Hellooooo!!
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.