In this tutorial, we will learn more about using variables in Linux & will also create some simple bash scripts utilizing global environment variables & local variables. As mentioned in our earlier tutorial, we can create a local variable the following way,

# new_variable=”test-value”

Example:

# school=’THE LINUX GURUS’

Recommended Read: How to setup SSH login without password on Linux systems

Also Read: Bash scripting – 3 – Performing Arithmetic Operation in shell script

Using local Variables in Linux

Now let’s create a simple script utilizing this and another local variable,

#!/bin/bash

NAME=”Prince DAN”

SCHOOL=”THE LINUX GURUS”

echo $NAME

echo $SCHOOL

echo “My name is $NAME & i am a teacher at $SCHOOL”

Save the script & close the editor. Now before we execute this script, please read the following points,

1- ‘#1/bin/bash’ is called as shebang & it tells the interpreter that following lines are written & to be executed in bash,

2- To call or to use variables in the script, we use ‘$’ followed by the name of variables,

3- lastly we need to provide the execute permissions to the script to run it. Use the following command to provide the rights,

# chmod +x simple_script.sh

Now that we have to execute the script, & the output will be,

# sh simple_script.sh

Prince DAN

THE LINUX GURUS

My name is Prince DAN & i am a teacher at THE LINUX GURUS

Using global variables in scripts

So we already have some environment variables setup by default on all the Linux machines. Some of these variables are, UID, USER, HOME (you can get complete list with the ‘set’ command). Now let’s utilized these variables,

# vi simple_script_2.sh

Create the following script,

#!/bin/bash

echo “ Current user is : $USER “

echo “ $USER has $UID UID”

echo “ & his home path is $HOME”

Save the file & execute the script, output will be,

# ./Simple_script_2.sh

Current user is: test-user

test-user has 453 UID

& his home is /home/test-user

Notice that we have not declared the values for mentioned variables in our script & values are being captured from the environment variables.

Using command substitution in variables

Command substitution is another way we can utilize variables, so with command substitution we will assign the output of a command as the value for a variable,

# new_date=$(date +%y%m%d)

echo $new_date

The same can be utilized in the scripts as well. This is all for now on using variables in Linux.We will discuss more about bash scripting in our coming tutorials, please feel free to share the tutorial or send in any questions or queries using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.