How to use variables in shell scripting

How to use variables in shell scripting

In this tutorial I will show you, how to use variables in shell scripting.

Lets create variables and set values to variables. This is an easy thing to do, but very important in shell scripting.

I will use echo to display the variable values.

How to create variables in bash scripting

Variable syntax: variable=value

Example 1:
OS=Linux

Some things you should know:

1: Do not use any space in the left and the right of equal “=” !!!

OS =Linux , OS= Linux, OS = Linux will all generate command not found errors.

2: Variable names are case sensitive !!! OS=Linux is not the same as Os=Linux

Example 2:
Kernel_vers=3.0

3: The assigned value must be placed in the right of the equal “=” sign!!! 3.0=Kernel_vers is will generate an error.

4: In your variable names, use only uppen and lower letters, numbers and underscores _ , the rest of the special characters may have different roles and mess up your commands.

How to display variable values with echo:

Syntax: echo $variable_name

The variables can also be displayed with printf, just like in C, but we will discuss about it in another tutorial.

No spaces before and after the equal “=” sign:

$ OS=Linux
$ echo $OS
Linux
$ OS =Linux

#the space placed in the left of the = causes errors
OS: command not found

The shell is case sensitive:

$ user=mike #only low cases
$ User=root #the first case is an upper
$ echo $user
mike
$ echo $User
root

Place the variable value only in the right side of the “=” sign:

$ Kernel_vers=3.0
echo $Kernel_vers=3.0
3.0

$ 3.0=kernel_vers
3.0=kernel_vers: command not found
#error generated by the misplacement of the value

Special characters in the variable names:

$ mike?=11
mike?=11: command not found # ? created this error
mike*=12
mike*=12: command not found # also * created an error
mike_id=1001
$ echo $mike_id
1001 #the underscore can be used in variable names

To remove the variable’s value use: echo variable_name=”” or unset variable_name.

The next shell scripting article is about the usage of the echo command in shell scripting.

Related reading about Linux / Unix environment variables:

Was this Tutorial helpful? Help others share on Facebook, Twitter, and Google Plus!

 
Enjoyed this video?
How to use variables in shell scripting
"No Thanks. Please Close This Box!"