In this tutorial we will learn about variables and cover some of the Shell Programming keywords.
These are named memory location to hold some value.
Variables inside a shell script dies as soon as the script ends executing.
To create a variable in shell script we have to keep the following points in mind.
a-z A-Z, digits
Nameare treated as two different variables even though they are same word.
To assign value to a variable we use the
= sign also called the assignment operator.
In the following example we are creating
message variable and assigning it a string value "Hello World".
For this we use the
read keyword followed by the name of the variable.
In the following example we are taking user input and saving it in variable
We use the
$ dollar sign to print the value stored in the variable.
In the following example we will print the value stored in the variable
These are the variables without any value. We can create one in the following manner.
x="" y='' z=
In the above code all three will create null variable having no value.
If we echo a null varibale then a blank line in shown in the terminal.
If we want to fix the value stored in a variable i.e., to make it readonly then we use the
The value of a readonly variable can't be changed later in the script.
To unset or erase the value and the variable from the shell memory we use the
In the following example we are unsetting the value and the variable
To create comments in shell script we start the line with a
# hash sign.
Comments are ignored when the script file is executed.
In this example we will create a
username variable that will hold the name entered by the user.
#!/bin/sh # take username echo "Enter username: " read username # greetings message message="Hello $username" # display greetings echo $message
Line 1: Shebang line.
Line 2: This is a comment line for us programmers and is ignored by shell.
Line 3: We are printing the string "Enter username:" using the
Line 4: Using the
read keyword to read user input and save it in a variable
Line 5: Empty line.
Line 6: Comment line.
Line 7: At this line we are creating another variable
message and assigning a string "Hello $username".
$username gives us the value stored in the variable username.
Line 8: Empty line.
Line 9: Comment line.
Line 10: At this line we are printing the value stored in the variable message.
$ sh username.sh Enter username: yusufshakeel Hello yusufshakeel