May 23, 2021 UNIX Getting started
A variable is a string that is assigned. T he value assigned to a variable can be a number, text, file name, device, or other type of data.
In essence, a variable is a pointer to the actual data. S hells can create, assign, and delete variables.
Variable names can contain only letters, numbers, or underscores.
By convention, the variable names of UNIX shells are capitaled.
Here are some examples of valid variable names:
_ALI
TOKEN_A
VAR_1
VAR_2
Here are some examples of invalid variable names:
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
Cannot be
!
The
*
the
-
, - and so on is that they have special uses in the shell.
Variables can be defined as follows:
variable_name=variable_value
Like what:
NAME="Zara Ali"
The above example defines the variable NAME and then assigns "Zara Ali". This type of variable is a regular variable that can only be assigned one at a time.
Shells can be assigned as they please. Like what:
VAR1="Zara Ali"
VAR2=100
In order to get the value stored in the variable, you need to add $before the variable name.
For example, the following script can access the value in the variable NAME and then print it to STDOUT:
#!/bin/sh
NAME="Zara Ali"
echo $NAME
The following values appear:
Zara Ali
Shell uses read-only commands to provide read-only functionality for variables. Such variables cannot be changed.
For example, in the following script, the value of the variable NAME is modified and the system reports an error:
#!/bin/sh
NAME="Zara Ali"
readonly NAME
NAME="Qadiri"
The following results occur:
/bin/sh: NAME: This variable is read only.
The deletion of a variable tells the shell to remove the variable from the list of variables so that it cannot be tracked. Once the user deletes a variable, it cannot be accessed and stored in the variable.
Here's an example of using the unset instruction:
unset variable_name
The above instruction cancels the defined variable. Here's a simple example:
#!/bin/sh
NAME="Zara Ali"
unset NAME
echo $NAME
The above example does not display any information and cannot use the unset instruction to cancel variables that are marked as read-only.
When a shell script is executed, there are three main types of variables: