Chapter 2. Working with Variables

This chapter will show how variables are used in a Linux system and in scripts.

The topics covered in this chapter are:

  • Using variables in scripts
  • Validating parameters using conditional statements
  • Comparison operators for strings
  • Environment variables

Using variables in scripts

A variable is simply a placeholder for some value. The value can change; however, the variable name will always be the same. Here is a simple example:

   a=1

This assigns the value 1 to variable a. Here's another one:

   b=2

To display what a variable contains use the echo statement:

   echo Variable a is: $a

Note

Notice the $ preceding the variable name. This is required in order to show the contents of the variable.

If at anytime, you aren't seeing the results you expect first check for the $.

Here's an example using the command line:

$ a=1
$ echo a
a
$ echo $a
1
$ b="Jim"
$ echo b
b
$ echo $b
Jim

All variables in a Bash script are considered to be strings. This is different than in a programming language such as C, where everything is strongly typed. In the preceding example, a and b are strings even though they appear to be integers.

Here's a short script to get us started:

Chapter 2 - Script 1

#!/bin/sh
#
# 6/13/2017
#
echo "script1"

# Variables
a="1"
b=2
c="Jim"
d="Lewis"
e="Jim Lewis"
pi=3.141592

# Statements
echo $a
echo $b
echo $c
echo $d
echo $e
echo $pi
echo "End of script1"

And here is the output when run on my system:

Chapter 2 - Script 1

Since all of the variables are strings I could have also done this:

a="1"
b="2"

It is important to quote strings when they contain blank spaces such as variables d and e here.

Note

I have found if I quote all the strings in my programs, but not the numbers, it is easier to keep track of how I am using the variable (that is, as a string or a number).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset