Dr. Mark Humphrys

School of Computing. Dublin City University.

Home      Blog      Teaching      Research      Contact

Search:

CA216      CA249      CA318

CA400      CA651      CA668


Arithmetic in Shell

Complex data structures do not exist in Shell.
But arithmetic is possible.



Arithmetic in bash

#!/usr/bin/bash

for (( i=1 ; i <= 10 ; i++ ))
do
 echo $i
done

j=5		 
echo $j
(( j++ ))
echo $j
(( j = $j + 1 ))
echo $j




Arithmetic in ksh

ksh (Korn shell) also has data types.
#!/usr/bin/ksh

integer i

i=1
echo $i
i=i+10
echo $i
i=i-4
echo $i
i=i*4
echo $i
i=i/2
echo $i




Other ways of doing arithmetic in Shell

In Shell you have TAG=VALUE pairs of text strings.
So you can set simple flags:
 flag=0

 if condition
 then
  flag=1
 fi

You can test if equality and inequality conditions are true.
For instance, test if the argument is less than 50:
 if test $1 -lt 50
Using the "expr" command, you can do arithmetic:

# x = $1 + $2

x=`expr $1 + $2`


So despite the fact that the Shell environment variables here are only text strings, and have no types, we can use other programs (test, expr) that interpret their text string arguments in certain ways, and so we can use them as numeric types after all.



Example

We can write the following in Shell:

flag=0
echo $flag

while test $flag -lt 30
do
 flag=`expr $flag + 1`
 echo $flag
done

which is equivalent to the following in C++:
int flag = 0;
cout << flag << "\n";

while ( flag < 30 )
{
 flag++;
 cout << flag << "\n";
}

The C++ program will run a lot faster of course!


Question - Why does the C++ program run a lot faster?

Hint:

$ which expr
/bin/expr

$ ls -l /bin/expr
-r-xr-xr-x   1 bin      bin        20988 May  3  1996 /bin/expr
  flag++;  
= say 3 machine instructions (what 3?)
30 times this = 90 machine instructions.

  flag=`expr $flag + 1`  
= say 300 machine instructions (why?)
30 times this = 9000 machine instructions.



bc (command-line calculator)

  

Other



Feeds      w2mind.org

On Internet since 1987.