Shell Programming Beginners Class Lesson 2 - Variables
February 15th, 2007
This is the second installment of Shell Programming Beginners Class. The first installment was on motivation.
Variables are the heart of programming. They allow you to do something with a value which you do not know. In practical terms lets say we have a program or script which takes one integer value (Ex: 1, 2, 3, 4, …) and simply adds 1 to that value. You give it 5, it gives you 6. Not very useful. However, in that program you are going to have to call whatever number the user gives you something. When writing the program you obvivously do not know what value the user is going to enter. They may not even enter an integer. Lets assume they will indeed give you an integer, for now. Whatever you call the number which the user gives you is the name of the VARIABLE.
Lets say I call the user inputed value IN_INT, then my variable name would be IN_INT. In BASH when I wanted to use the value of that variable (Ex: 6 ) then I would prefix the variable name with a dollar sign, $.
Here is our sample program: (All your programs must start with #!/bin/bash and must be executable, chmod 744 filename.)
# cat addOne.sh
#!/bin/bash
echo "Type an integer and press enter: "
read IN_INT
echo "You entered $IN_INT to the program."
echo "Here is your output master: " `expr $IN_INT + 1`
I will run the script:
# ./addOne.sh
Type an integer and press enter: 6
You entered 6 to the program.
Here is your output master: 7
Following along? If not send me an email: .
In BASH variables can be numbers or strings. Example:
# STR1="this is a string."
# echo $STR1
this is a string. # STR2=THIS_IS_A_STRING_WITH_NO_SPACES
# echo $STR2
THIS_IS_A_STRING_WITH_NO_SPACES# INT1=21
# echo $INT1
21
You can also assign the output of a command to a variable with the ` or backtick character:
# pwd
/root
# CWD=`pwd`
# echo $CWD
/root
You can perform mathematic operations on variables in a few different ways. The simplest is the expr command. expr allows you to add, substract, multiply, divide, find remainders, test values against other values, and a whole range of other things. I used expr above to add one to a number. Read the manual page of expr if would like to learn more.
If you would like to learn more please read the next article in this series Shell Programming Beginners Class Lesson 3 - Essential Commands.


Leave a Reply