Variables in shell Scripting

Shell Linux Bash scripting

What is a variable in shell scripting ?

A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.

A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.

 

Variable Names:

The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).

The following examples are valid variable names 

 

_MJIT

COURSES_IT

VAR_1

VAR_2

Following are the examples of invalid variable names −

2_VAR

-VARIABLE

VAR1-VAR2

VAR_A!

The reason you cannot use other characters such as !*, or - is that these characters have a special meaning for the shell.

 

Become Master In Ansible Click here

 

Defining Variables

Variables are defined as follows 

variable name=variable_value

NAME="mjit"

 

To access the value stored in a variable, prefix its name with the dollar sign ($)

 

#!/bin/bash
NAME=” WELCOME TO MAHO JASE INSTUTITE OF TECHNOLOGY”
echo$ NAME
 

output:

variables definition

 

learn python click here

Assingning a variable value to another variable

#!/bin/bash
value1=20
value2=value$1
echo " The resulting value is $value2

 

Output:

chmod

Types of Variable Types:

Three Types of varibles 

 

Local Variables − A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at the command prompt.

 

Environment Variables − An environment variable is available to any child process of the shell. Some programs need environment variables in order to function correctly. Usually, a shell script defines only those environment variables that are needed by the programs that it runs.

 

Shell Variables − A shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly. Some of these variables are environment variables whereas others are local variables.

Use of Backtick symbol (`) in shell variables:

The backtick allows you to assign the output of a shell command to a variable. While this doesn’t seem like much, it is a major building block in script programming. You must surround the entire command line command with backtick characters:

DAY=`date'

 

 

#!/bin/bash
DAY=`date
value2=value$1
echo " Today date and time is $DAY"

 

backtick

Become Devops Engineer click here