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.
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 gameScore.
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 gameScore.
These are the variables without any value. We can create one in the following manner.
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 readonly keyword.
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 unset keyword.
In the following example we are unsetting the value and the variable tempResult.
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.
# take username
echo "Enter username: "
# greetings message
# display greetings
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 echo keyword.
Line 4: Using the read keyword to read user input and save it in a variable username.
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".
Note! The $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
Have fun learning :-)
Copyright © 2014 - 2019 DYclassroom. All rights reserved.
rendered in 0.0143 sec