In this article I will show you how to 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
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
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:
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:
$ echo $OS
$ 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
$ echo $User
Place the variable value only in the right side of the “=” sign:
3.0=kernel_vers: command not found
#error generated by the misplacement of the value
Special characters in the variable names:
mike?=11: command not found # ? created this error
mike*=12: command not found # also
* created an error
$ echo $mike_id
#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: