Unix
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
0-9
_
name
Name
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".
message
message="Hello World"
For this we use the read keyword followed by the name of the variable.
read
In the following example we are taking user input and saving it in variable gameScore.
gameScore
read 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.
echo $gameScore
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 readonly keyword.
readonly
readonly a=10
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.
unset
In the following example we are unsetting the value and the variable tempResult.
tempResult
unset 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.
username
Script: username.sh
#!/bin/sh # take username echo "Enter username: " read username # greetings message message="Hello $username" # display greetings echo $message
Explanation:
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.
echo
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.
$username
Line 8: Empty line.
Line 9: Comment line.
Line 10: At this line we are printing the value stored in the variable message.
Output:
$ sh username.sh Enter username: yusufshakeel Hello yusufshakeel