User Define Variables
A variable is a character string to which we assign a value.
A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.
Rules:
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).
Variable names cannot be reserved words
Variable names cannot have whitespace in between
The variable name cannot have special characters.
The first character of the variable name cannot be a number.
By convention, Unix shell variables will have their names in UPPERCASE.
The following examples are valid variable names −
_VARIABLE_NAME
VARIABLE_NAME
VARIABLE_1_NAME
vARIABLE_2_NAME
Following are the examples of invalid variable names −
2_VARNAME
-VARIABLENAME
VARIABLENAME-SOMENAME
SOMENAME_A!
The reason you cannot use other characters such as !, *, or - is that these characters have a special meaning for the shell.
Defining Variables
Variables are defined as follows −
variable_name=variable_value
For example −
MY_MESSAGE="Hello World"
Note that there must be no spaces around the "=" sign: VAR=value works; VAR = value doesn't work. In the first case, the shell sees the "=" symbol and treats the command as a variable assignment. In the second case, the shell assumes that VAR must be the name of a command and tries to execute it.
#!/bin/bash
# variable.sh.
# user Define Variables.
name="Saurav"
age="20"
echo ${name}
echo "my name is ${name} and my age is ${age}"
# echo 'my name is ${name} and my age is ${age}'
work="programm"
var="ing"
echo "i am $working"
echo "i am ${work}ing"
echo "i am ${work}${var}"
let's see the output of above shellscript
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./variable.sh
Saurav
my name is Saurav and my age is 20
i am
i am programming
i am programming
#!/bin/bash
# variable_name.sh
_variableName="first variable"
variable2Name="second variable"
name="gaurav"
NAME="saurav"
nAmE="amit"
echo "${name} ${NAME} ${nAmE}"
echo "${_variableName}"
echo "${variable2Name}"
variable_name="vartest"
echo "${variable_name}"
# 3namevariable="myname"
# echo "${3namevariable}"
my-name="gaurav"
echo "${my-name}"
let's run the above program
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./variable_name.sh
gaurav saurav amit
first variable
second variable
vartest
./variable_name.sh: 22: my-name=gaurav: not found
name