Insights to Local Variable in Bash [4 Practical Examples]

Local variables are crucial elements in Bash scripting. These specify the variables that are used to store and manipulate data within a limited scope (a specific function or code block). In this article, I’m going to demonstrate what a local variable is and how it performs different practical tasks and maintains data integrity in Bash. Let’s dive into it!

What is a Local Variable in Bash?

A local variable is nothing but a variable that is declared and utilized within a defined scope, such as within a block of code or function. These variables are designed with a confined visibility and you can access them within a bounded scope in which they are defined.

Local variables help encapsulate data, avoid naming conflicts, maintain high data integrity and refine program collocation in Bash scripts. Typically, these variables don’t interfere with the variables in global scope having the same name.

Why Use Bash Local Variable?

No doubt, local variables aid in promoting code structure and reducing unintended bugs in Bash scripts. Here are some core facts about why one should use local variables in Bash:

  • Allow Data Encapsulation

Local variables allow you to encapsulate data effectively within a specific scope. Specially, when you need to store any temporary data that are only relevant within a part of your code, directly employ local variables with no hesitation.

  • Prevent Unintended Conflicts

Local variables are only accessible from the defined scopes within a function which ensures that the value of the local variable is only confined to that specific function and it doesn’t affect the outside of the function. This helps reduce the risk of naming conflicts and prevent unintended changes to global variables in wider scopes.

  • Reduce Global Clutter

Too many global variables result in clutter and global pollution making it hard to keep the right track of the declared variables throughout the script. In this effort, local variables are the ones that reduce the risk of global pollution with unnecessary variables.

  • Avoid Parallel Interference

Using local variables helps avoid parallel interference when writing scripts that involve multiple concurrent processes running in the background. As local variables are confined only to a specific function within the script, each process operates independently and doesn’t affect the variables in other processes.

  • Enhance Security

Local variables ensure sensitive data protection by limiting its visibility to a local context. While dealing with a variable that contains sensitive data like an API key or user password, using local variables is crucial for minimizing its scope and reducing the risk of unexpected bugs or accidental exposure.

4 Examples of Local Variable Implementation in Bash

In Bash scripting, local variables can be used for various purposes like data processing, temporary file operation, loop iteration, error handling and so on within functions. The following section is a clear illustration of such examples of local variable implementation in Bash:

Example 1: Data Processing & Manipulation Using Local Variable in Bash

You can use local variables to process and manipulate data within a function. The following is a step-by-step interpretation of data processing using string substitution that describes how local variables can manipulate data within the local scope of a function. Let’s see the example:

Steps to Follow >

➊ Go to Ubuntu Terminal, open a script in the Nano text editor by running the following command:

nano data.sh
EXPLANATION
  • nano: A text editor.
  • data.sh: This is a script. Here, I have named the script ‘data.sh’. You can name any of your choices.

Opening the file in Nano text editor

➋ Now, write the following script inside the editor:

Script (data.sh) >

#!/bin/bash

data() {
  local data="$1"
  #Manipulating the local variable
  local new_data="${data//Windows/Linux}" #Performing string substitution
  echo "Data after processing: $new_data"
}
input="HelloWindows"

#Calling the function
data "$input"
EXPLANATION

In #!/bin/bash, ‘#!’ is called Shebang’ or ‘Hashbang. Here, the script defines a function called ‘data’ and declares a variable with a single input data assignment. Then, it manipulates data by performing string substitution where all occurrences of ‘Windows’ are replaced with ‘Linux’ and stores the result in a new local variable. Finally, the script displays the processed data by employing the echo command.

➌ Then, press CTRL+S to save the file & press CTRL+X to exit.

➍ After that, use the command below to make the script executable:

chmod u+x data.sh
EXPLANATION
  • chmod: Changes the permission of the files and directories.
  • u+x: Adds the executable permission for the user.
  • data.sh: The file which you want to make executable.

Adding executable permission to the script

➎ Finally, run the script by the following command:

./data.sh

Output of data processing using local variable

From the image, you can see that the data in the script has been processed using the local variable.

Example 2: Temporary File Operation Using Local Variable in Bash

For any kind of temporary file operations, you can use local variables. Generally, temporary files are used for temporary data storage where local variables specify a particular scope of function that holds the specific path of the file and other related operations. Here’s an example:

You can follow the Steps of Example 1, to save & make the script executable.

Script (temp.sh) >

#!/bin/bash

temp_file() {
  local temporary_file
  #Creating a temporary file
  temporary_file=$(mktemp)
  #Removing the temporary file
  rm "$temporary_file"
  echo "Removed the temporary file: $temporary_file"
}

#Calling the function
temp_file
EXPLANATION

The above script declares a function called ‘temp_file’ and creates a temporary file within it using the ‘mktemp’ command. Then, it removes the created temporary file promptly by using the ‘rm’ command. Finally, the script echoes a message as an indication of temporary file removal.

Now, run the script by the following command:

./temp.sh

Output of removing temporary file using local variable

From the image, you can see that the temporary file has been removed by employing a local variable.

Example 3: Loop Iteration Using Local Variable in Bash

While working with loops within a function, it’s very easy to use local variables to iterate through the arrays and operate each element. A simple demonstration is given below:

You can follow the Steps of Example 1, to save & make the script executable.

Script (loop.sh) >

#!/bin/bash

iterate_loop() {
  local array=("$@")
  #Looping through the array
  for item in "${array[@]}"; do
    echo "Processing the item: $item"
  done
}
array_items=("Linux" "Windows" "Mac")

#Calling the function
iterate_loop "${array_items[@]}"
EXPLANATION

Here, the script defines a function ‘iterate_loop’ expecting an array as its argument. Within the function, the script declares a local variable and assigns the array to it and then a ‘for’ loop is used to iterate through the array elements. Finally, it displays the outputs using the echo command.

Now, run the script by the following command:

./loop.sh

Output of loop iteration using local variable

The above image dictates how you can employ local variables within loops to iterate through array elements.

Example 4: Error Handling Using Local Variable in Bash

Availing local variables for error handling within a function is an effective and organized process as the variable’s scope remains limited to that specific function only. For instance:

You can follow the Steps of Example 1, to save & make the script executable.

Script (error.sh) >

#!/bin/bash

trigger_error() {
  local error="$1"
  echo "Error message: $error"
}

#Simulating an error condition
if [ ! -d /home/nadiba/color ]; then
  trigger_error "Directory not found."
fi
EXPLANATION

This script defines a function called ‘trigger_error’ that awaits a single argument. Within the function, the script declares a local variable and assigns the first argument passed to the function to it. Lastly, the script simulates an error condition and uses the echo command to display the error message.

Now, run the script by the following command:

./error.sh

Output of error handling using local variable

The above image depicts an error message as an indication of the error-handling operation using a local variable within a function.

Conclusion

Wrapping up, local variables are useful for managing data within particular scopes, controlling data integrity and availing consistent and assembled Bash scripting practices.

People Also Ask

Can two functions have local variables with the same name in a Bash script?

Yes, two functions can have local variables with the same name in a Bash script.

Does it require specifying the data type while declaring a local variable in Bash?

No, as variables are dynamically typed in Bash, it doesn’t require specifying the data type while declaring a local variable.

Are local variables in Bash case-sensitive?

Yes, local variables in Bash are case-sensitive.

Can recursive functions in Bash use local variables?

Yes, recursive functions (functions that call themselves to perform a task) in Bash can use local variables.

Related Articles


<< Go Back to Variable Scopes in Bash | Bash Variables | Bash Scripting Tutorial

5/5 - (1 vote)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment