| < Day Day Up > |
|
In addition to getting input from the user, you often will want to perform some basic arithmetic operations. This is a place where scripts can be particularly useful. If you have some calculations you need to perform on a regular basis, you can use a script to automate that task. The generic syntax used is this:
expr operator1 math-operator op2
For example, you can add two numbers by typing in
expr 20 +2
The math you can do in a Linux shell script is very limited. Essentially you can do very simple arithmetic operations on two operators. One or both of the operators can be a variable, so you could write a script that asks the user for two numbers and adds or subtracts them. For more advanced math you will need a more advanced scripting language, and that is beyond the scope of this book. However, let’s take a moment to look at a script that does use the limited math capabilities available. Type the following into the text editor of your choice and save it as scriptseven.sh:
#!/bin/bash numone=0 numtwo=0 echo Please enter the first number read numone echo Please enter the second number read numtwo echo $numone added to $numtwo is `expr $numone + $numtwo` exit 0
When you run this script, you should see something much like what is displayed in Figure 20.12.
Figure 20.12: Basic script math.
Admittedly this is not particularly advanced math or even very interesting! But it does illustrate the very basic arithmetic capabilities of a Linux shell script. You may have noticed what appear to be single quotes on each side of the expr $numone + $numtwo statement. These are not actually single quotes, they are backquotes. On most keyboards, to the left of the number one key, you will see a key that has a ~ and a ` mark. The first is called a tilde, and the second is the backquote. It is imperative that you use the backquote rather than the single quote that is to the right of your colon/semicolon key.
| < Day Day Up > |
|