DEV Community

Cover image for Continuation to Shell Scripting: Variables and Their Scope (Day 9)
Kenneth Mahon
Kenneth Mahon

Posted on

Continuation to Shell Scripting: Variables and Their Scope (Day 9)

Bash variables provide temporary storage for information. You can use them to store words/phrases (strings), decimals or integers.

Variables
To assign a variable, we use the = symbol
NOTE:

  • When you assign a value to a variable, there should not be any spaces on either side of the = symbol.

  • When we want to access a variable, we need to use the $ symbol to reference it

name="Kenneth"
echo $name

let's add variables to bash script

variables added to our bash script

Result of the added variables

Because our variables may contain whitespace which gets interpreted by bash, it’s good practice to wrap the variable name in curly brackets and encase it in double quotes just like the way we represented it in our diagram above

In Bash, if you try to access a variable that doesn’t exist, you won’t see an error, just a blank value. For Example:

variables

Result
You can see variable 1 value was left blank because the variable was not declared

Variable scope

There are two types of variable:

  • Local variables

  • Global variables

Local variables

Local variables are only accessible within the section of code in which they are declared. For example, if we declare a variable inside our Bash script, it will not be accessible outside of that script. using the example we used before, let try to call "var2" outside of the script, directly in our terminal

Result
you can see after calling var2 directly on the terminal, it gave us a blank result and this is due to the fact that the scope of our variable was constrained to the script itself and its value is not accessible outside of that script.

Global variables

You can create your own global variables by using the export command. First let’s declare a variable directly on our Terminal:

Result

Next, let’s create a script that tries to access this variable:

Output

If we run this script, our result will be blank. variable we created was only a local variable and therefore not accessible within our script.

Output

However, if we use the export command, we can declare MY_NAME as a global variable which is accessible in our script and when we run it, we will have the value assigned to it .
Here we go:
Result

That is it for Day 9. time to practices more on this. see you all tomorrow for Day 10

Top comments (0)