facebook youtube pinterest twitter reddit whatsapp instagram

Local Variable, Typset and The Declare Command In Bash

Local variables are private inside of a function and the most important thing about a local variable is that when it is changed in a function, it doesn't affect the variable outside of a function.

If you only need a variable in a specific function then it is a good idea to declare them a local, and this is done with the typeset command or the declare command.

Typeset Command

With the typeset command, you can make a variable local, you can provide type or can provide formatting.

So, if the variable is only going to have integer values, then you use the following:

typeset -i a

the i stand for integer and thus makes 'a' an integer.

The good thing about doing things this way is that it makes your code much more faster and cleaner.

Here are more declaration you can do with the typeset command:

  • typeset -l: All upper-case characters are converted to lower-case. The upper-case flag, -u is turned off.
  • typeset -u: All lower-case characters are converted to upper-case characters. The lower-case flag, -l is turned off.
  • typeset -r: The given names are marked read-only and these names cannot be changed by subsequent assignment, that is you can't assign it a new value
  • typeset -t: Tags the variables. Tags are user definable and have no special meaning to the shell.
  • typeset -x: The given names are marked for automatic export to the environment of subsequently executed commands.

Additionally, if you declare a variable as an integer you'll be able to use some integer operations with them, for example:

  • id++, id-- variable post-increment, post-decrement
  • ++id, --id variable pre-increment, pre-decrement
  • ** exponentiation
  • *, /, % multiplication, division, remainder
  • +, - addition, subtraction
  • <=, >=, <, > comparison
  • ==, != equality, inequality
  • && logical AND
  • || logical OR

Something worth mention is the post-increment and the pre-increment, basically, Increment operators are used to increase the value by one while decrement is the opposite of increment; decrease the value by one.

When using a post-increment (e.g i = x++), it means first assign the value of 'x' to 'i', then increment x, which is why we have post;after. Pre-increment (e.g i = ++x) means increment x first and then assign the value of x to y straight away. Let's take an example, say you have the following:

i = x++;

If the value of ‘x’ is 5 then value of variable ‘i’ will be 5 because old value of ‘x’ is used, remember post means after.

If you have the following:

i = ++x;

If the value of ‘x’ is 5 then value of variable ‘i’ will be 6 because the value of i gets incremented before using it in a expression.

The Declare Command

The declare command is the same as the typeset command, the only difference is that the declare command is new and the typeset is obsolete, so, you might want to start using the declare command instead of the typeset command.

Since the declare command is the recommended one, let's take a quick example:

#!/bin/bash
function testlocal { # Line 1
   declare x         # Line 2
   x=5               # Line 3
   y=10              # Line 4
}                    # Line 5
x=1                  # Line 6
y=2                  # Line 7
echo x is $x         # Line 8
echo y is $y         # Line 9

testlocal            # Line 10

echo x is $x         # Line 11
echo y is $y         # Line 12

Let's decipher the code one after the order:

On Line 1, we define a function called testlocal, and inside the function we make a local variable called x (line 2), when you use the declare command inside a function, it makes the variable local, meaning it is visible only within the block of code in which it appears. It has local scope, and thus has meaning only within that function block.

Still inside the function (line 3 - 4), we set x=5, and y=10, again, the x is private to the function, and we did not declare y as local, so y could change outside of a function if there is one.

Outside of the function (line 6 -7), we set x=1, and y=2, and we then echo both of them(line 8 - 9).

On the next line(line 10), we summon the function testlocal, function testlocal will then assign x=5, and y=10, then after we return from the function, we print out x and y, and here is the output:

user@server: testlocal.sh
x is 1
y is 2
x is 1
y is 10
user@server:~/bin$

You see that the x doesn't change, it still has the vaue of the outside variable, which means x only has meaning to that function, now try this example:

#!/bin/bash
function testlocal {
   declare x
   x=5
   y=10
echo x is $x
}
x=1
y=2
echo x is $x
echo y is $y
echo         # Print empty line
testlocal 
echo         # Print empty line
echo x is $x
echo y is $y

Now, we got the following output:

user@server:~/bin$ testlocal.sh
a is 3
b is 2

a is 5

a is 3
b is 10

Now, you can see we got the value of the local variable printed 'a is 5', so, to sum it up a local variable only has meaning to the function.

Here are more examples:

Convert a String to Lower Case

#!/bin/bash
declare -l lstr="I LOve jack"     # This convert the string to lower case

echo lstr = $lstr

Output

lstr = i love jack

Convert a String to UpperCase

#!/bin/bash
declare -u ustr="i love jack"     # This convert the string to upper case

echo ustr = $ustr

Output

ustr = I LOVE JACK

Mark a Variable Value as Read-Only

#!/bin/bash
declare -r readonly="First Value" # Makes it read-only, you can't assign it a new value

echo readonly = $readonly 
readonly="New Value"     # Trying to add a new value to the variable marked as read-only

Output

readonly = First Value
user@server:~/bin$ readonly="New Value"
-bash: readonly: readonly variable

You get it is a "readonly variable" because the variable as been marked as so.

Related Post(s)

  • sed (Stream Editor) In Bash Scripting

    Another powerful filter in GNU/Linux is sed (stream editor), which is a program for performing basic editing tasks on the output of another program or on a file. sed or stream editor can be used to p

  • awk In Bash Scripting

    Up until now, we have covered a couple of text processing, from sed to grep to sort, and now we have the big daddy, which is awk. awk (which stands for Aho, Weinberger, and Kernighan - its creators)

  • (Bash Script) Automate Multiple Classicpress & Wordpress Installation + [Caching and SSL]

    If you are tired of using control panels (I am because they are mostly not secure, and most comes loaded with bundles of useless stacks), and want to do everything on the server level, I wrote a menu

  • Returning Values From Functions in (Bash)

    In the guide function in bash, we dive deep in bash functions and we also pass some information into the functions to carry out a certain operation. In this guide, I'll show you how to get informatio

  • Functions in Bash

    Functions are modular building blocks for creating powerful and modular scripts, using function makes it easy to isolate a code since it would be in a single building block, which would be isolated f

  • Understanding The Four (4) Ways Command-Line Runs Shell Script

    Sometimes we need to think like the command line shell in order to understand how things are done in the background, this would make debugging a breeze. In this guide, you would learn all the variou