top of page

Bash Scripting - Variables

Variables will be very familiar to those of you who have spent some time in programming before. Consider a variable as a temporary storage location for a single piece of data if you haven't already. These variables are extremely useful for managing and controlling the actions of our Bash script. We'll look at a variety of different ways that variables get their data and how we can use it.


Variables are one of those things that are both simple to use and simple to get into trouble with if you don't fully comprehend how they work. As a result, this section requires some reading, but if you take the time to read it and understand it, you will be glad you did later on when we begin working with more complex scripts.


When it comes to dealing with variables, we have two options:

  1. The act of assigning a value to a variable.

  2. Reading a variable's value.

The value of variables can be set in a variety of ways. The most common methods are to set the value directly and to set the value as a result of command or program processing, Here are a few quick syntax tips:

  • We don't use the $ sign when setting a variable.

  • We use a $ sign before the variable name when referring to or reading it.

  • Some people prefer to write variable names in all caps to make them stand out. However, it is entirely up to you. They can be all capital letters, all lowercase letters, or a mix of both.

  • A variable can be used anywhere in a script (or on the command line), and Bash will replace it with the value of the variable when it is run.



What happens when we run the bash script?

  • It checks for the variables which are defined in the script.

  • Interprets code line by line.

  • It then replaces the variable names with their assigned values.

  • Finally, execute the code line by line by repeating the above process.

Syntax to declare the variable or set its value

Declaring or setting the value of a variable is fairly simple. The basic syntax is as follows:

variableName=value

Note: If the variable's value contains spaces, use quotes to define them (var1="David Tzemach")

Naming variables

When naming a variable, keep the following rules in mind:

  • Because variables are case sensitive, "AAA" and "aaa" are two distinct variables.

  • Variables must not begin with a number.

  • When defining a variable name, do not use any special characters.

  • Variables can start with an alphanumeric character or underscore and end with a letter, number, or underscore.



Examples of Code


Example 1:

let's start with a simple example that demonstrates how to create variables, assignee values, and print them:

#! /bin/bash
#Defining a new variables and assigning value

#Lets define two variables and assigned values
myname=David
Mylastname=Tzemach

#Lets print it
echo My personal name is "$myname" and my last name is "$Mylastname"

Lets run it...

[root@scriptbox scripts]# ./varscript.sh
My personal name is David and my last name is Tzemach

Please note that if you use the variable name without $,sign it prints the value as the variable name rather than getting the value of variable


We can also use variables directly on the console, for example:

[root@scriptbox ~]# package="httpd wget unzip"
[root@scriptbox ~]# yum install $package -y

Example 2:

let's take what we learned and create a package deployment script, the original script without variables is:

#!/bin/bash

#intall wget and unzip it, we use sudo in case we run it with non-adminn user
sudo yum install wget unzip httpd -y
# we are using dev/null to reduce user notification while errors will be displayed on the screen

#Start HTTPD
echo "Start & Enable HTTPD Service"
sudo systemctl start httpd
sudo systemctl enable httpd

#Creating TMP folder to host file, we will use p attribute in case the folder already exists

Let us now change it with variables:

#!/bin/bash

# Variable Declaration
PACKAGE="httpd wget unzip"
SVC="httpd"
URL='https://www.tooplate.com/zip-templates/2098_health.zip'
ART_NAME='2098_health'
TEMPDIR="/tmp/webfiles"


#intall wget and unzip it, we use sudo in case we run it with a non-admin user
sudo yum install $PACKAGE -y
# we are using dev/null to reduce user notification while errors will be displayed on screen

#Start HTTPD
echo "Start & Enable HTTPD Service"
sudo systemctl start $SVC
sudo systemctl enable $SVC

#Creating TMP folder to host file, we will use p attribute in case the folder already exists
mkdir -p $TEMPDIR

#Moving to folder
cd $TEMPDIR

echo "Downloading Template"
#Downloading template and unzip it
wget $URL
unzip $ART_NAME > /dev/null

#Copy file content
sudo cp -r $ART_NAME/* /var/www/html/


Command Line arguments

The system sets a few variables that are worth mentioning:

  • $USER - The username of the user running the script.

  • $HOSTNAME - The hostname of the machine the script is running on.

  • $SECONDS - The number of seconds since the script was started.

  • $RANDOM - Returns a different random number each time is it referred to.

  • $LINENO - Returns the current line number in the Bash script.

  • $0 - The name of the Bash script.

  • $1 - $9 - The first 9 arguments to the Bash script. (As mentioned above.)

  • $# - The total number of arguments passed to the Bash script.

  • $@ - The entire set of arguments passed to the Bash script.

  • $? - The most recently run process's exit status.

  • $$ - The current script's process ID.

Example_1: $1 - $9

in the following example, we will pass arguments from the command line when running the script instead of explicitly using the existing variables.

#!/bin/bash

# Variable Declaration
PACKAGE="httpd wget unzip" 
SVC="httpd"
#URL='https://www.tooplate.com/zip-templates/2098_health.zip'
#ART_NAME='2098_health'
TEMPDIR="/tmp/webfiles"


#intall wget and unzip it, we use sudo in case we run it with a non-admin user
sudo yum install $PACKAGE -y
# we are using dev/null to reduce user notification while errors will be displayed on screen

#Start HTTPD
echo "Start & Enable HTTPD Service"
sudo systemctl start $SVC
sudo systemctl enable $SVC

#Creating TMP folder to host file, we will use p attribute in case the folder already exists
mkdir -p $TEMPDIR

#Moving to folder
cd $TEMPDIR

echo "Downloading Template"
#Downloading template and unzip it
wget $1
unzip $2.zip > /dev/null

#Copy file content
sudo cp -r $2/* /var/www/html/

So now when we run this script, we will have to provide two arguments:

[root@scriptbox scripts]# ./arg.sh Value_1 Value_2


Example_2: $?

Let's look at another example of how we can use $? to understand error codes during script execution. These are the standard error codes in Linux or UNIX.

  • 1 - Catchall for general errors

  • 2 - Misuse of shell builtins (according to Bash documentation)

  • 126 - Command invoked cannot execute

  • 127 - “command not found”

  • 128 - Invalid argument to exit

  • 128+n - Fatal error signal “n”

  • 130 - Script terminated by Control-C

  • 255\* - Exit status out of range


The first command we will run returns '0,' indicating that there are no errors.


[root@scriptbox scripts]# free -m total used free shared buff/cache available Mem: 990 154 90 6 746 682 Swap: 1023 0 1023 [root@scriptbox scripts]# echo $? 0


another examples (error codes 1 & 127):

[root@scriptbox scripts]# free12 -m
-bash: free12: command not found
[root@scriptbox scripts]# echo $?
127
[root@scriptbox scripts]# free -mnnnnn
free: invalid option -- 'n'

[root@scriptbox scripts]# echo $?
1



11 views0 comments
bottom of page