Introduction
A variable in the Unix environment is used to store values temporarily and use it during program execution.
A variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _). The standard practice is to use the variable name in UPPERCASE but it is not mandatory. We can write it in lowercase too.
For example: testVar, test1, var1 , 2var, _var
What are types of variables?
- Local Variables: These variables present within the current instance of the shell. These are not available to programs that are started by the shell. They are set at the command prompt.
- Environment Variables: These variables are available to any child process of the shell.
- 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. These can include environment variables and local variables.
Defining and Initiating Variables
The syntax for creating a variable is as below
variable_name = variable_value
Here variable 'country' is a scalar variable. A scalar variable can hold only one value at a time.
e.g. country=“India”
Unix shell enables us to store any value - like storing the integer value in the country_cd field
e.g. country_cd=100
How to access value from a variable?
To access value from a variable, we need to use the $ character before the variable name.
For example,
#!/bin/sh
NAME="Techno Guru"
echo $NAME
How to create the read only variable?
To mark variables as read only by using the readonly command.
The value of the readonly variable cannot be changed.
e.g.
#!/bin/sh
VAR="Techno Guru"
readonly VAR
VAR="Training"
How to unset variables?
- Unsetting or deleting a variable directs the shell to remove the variable from the list of variables that it tracks.
- Once we unset a variable, we cannot access the stored value in the variable.
- We cannot use the unset command to unset variables that are marked readonly
e.g.
#!/bin/sh
VAR="Techno Guru"
unset VAR
echo $VAR
The video below provides in-depth knowledge about how to use variables in the Unix environment with the demo.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.