Dr. Mark Humphrys School of Computing. Dublin City University. My big idea: Ancient Brain Search:

# 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)

• bc calculator
• man bc
• interactive mode
• also non-interactive (scriptable) mode:

 ```# powers echo "2^32" | bc # floating point operations # scale defines no. of decimal places echo "scale=2; 2347 / 19" | bc echo "scale=3; sqrt(50)" | bc # bc -l loads extra library: =========================== # e to the power echo "e(5)" | bc -l # sine echo "s(0)" | bc -l # calculate pi using the fact that: # arctan(1) = pi/4 echo "scale=100; 4*a(1)" | bc -l ```

• Q. How would you wrap a shell script around the above to make it easier to use?
```
```

# Other

• factor - factor a number:
```factor n
```
```

```

Feeds      w2mind.org      ancientbrain.com

On the Internet since 1987.