How to Use Integers in Linux
- 1). Open a text editor such as gedit. Enter the following as the first line of your script:
#!/bin/bash
This will allow the shell to recognize it as a bash script when you run it. - 2). Enter the following code two lines down from the first line:
declare -i n
This defines the variable "n" as being an integer. Normally, variables in bash are untyped, all functioning as strings but treated as numbers when necessary. Declaring a variable to be an integer makes it incapable of storing strings in the future but allows it to be used in ways untyped variables cannot. - 3). Enter the following two lines:
n=10/2
echo "The integer n now equals 10 divided by 2, namely $n."
Performing this operation on an untyped variable would actually set it to the string "10/2." To give it the value of 10 divided by 2, it would have to be written in one of the three following ways:
let "n=10/2"
n=$(( 10 / 2 ))
n=`expr 10 / 2`
Because n has been declared as an integer, however, it can use most arithmetic operators directly. - 4). Enter the following lines of code:
n=$RANDOM
n=n%20
let "m=n**2"
echo "After randomization, n equals $n, the exponent of which is $m."
This sets n to a random integer, using the mod operator to restrict it to values below 20. A normal untyped variable is set to the exponent of n and the values are displayed on the screen. Note how the mod operator is used reflexively. While all single-symbol arithmetic operators can be used directly by integers, the only self-affecting operator that can be so used is +=. The %= operator must be used as follows by both integers and untyped variables alike:
let "n%=20" - 5). Save the file as "script" in your /home directory and open a shell terminal. Enter the following two commands to make it executable and run it:
chmod 755 script
./script