A bit more with logic and the shell

doing arithmetic with expr

command/output explanation
$ n=17
$ echo $n+3 
______________
17+3      
"echo" takes things pretty literally
$ n=17
$expr $n + 2
_______________
19                
"expr" converts to numbers. Note the needed spacing around the plus sign.
$ n=17
$ expr $n - 2
15
$ expr $n / 2
8
$ expr $n "*" 2
34
Put the quotes around the '*' so it isn't viewed as a wildcard. Note that 17/2 is 8.

another trick for arithmetic in the shell

command/output explanation
$ echo $[ 3 * 4 ]
12
It works, but I'm not sure quite why.
$ echo $[9%4]
1
Using the modulus operator.

doing arithmetic with bc and goodies

command/output explanation
$ echo 17 + 2
17 + 2
$ echo 17 + 2|bc
19
$ echo 17 - 2|bc
15
Some results may be piped into bc.
$ echo 17 * 2|bc
17
$ echo '17 * 2'|bc
34
$ echo "17 * 2"|bc
34
Some expressions must be quoted.
$ echo "2/3"|bc
0
$ echo "scale=4; 2/3"|bc
.6666
$ echo "2/3"|bc -l
.66666666666666666666
Division doesn't always work the way you would hope. But there are workarounds.
$ echo "scale=10; 4*a(1)" | bc -l
3.1415926532
[ddailey]$ echo "s(3.141592653/2)" | bc -l
.99999999999999999995
You can also do really cool things. ("a" means arctangent; "s" means sine)
$ echo '21649 * 513239'|bc
11111111111
$ factor 11111111111
11111111111: 21649 513239
Prime factorizing has never been so easy.

 

while:

command/output explanation
$ cat count
n=16
while [ $n -lt 20 ]
do
        echo $n
        n=`expr $n + 1`
done

$ ./count
16
17
18
19                             
"-lt"  means "less than".

totaling a column of numbers

command/output explanation
$ sum=0
$ for i in `ls -ld a*|awk {'print $5'}`
> do
> sum=`expr $sum + $i`
> done
$ echo $sum
12719         
This totals the number of bytes in all files whose names begin with 'a'.

if:

command/output explanation
for i in `ls -dF *|sed 's/.*\///'`
> do
> a=`ls -l $i|awk {'print $5'}`
> if [ $a = 0 ]
> then
> echo $i $a
> fi
> done|more
aaaa 0
aaab 0
aaac 0
aaad 0
aaae 0
file1 0 
This finds and prints names of all empty files in a directory
$ cat testing
if [ $1 -eq 0 ] && [ ! $2 -eq 1 ]
then
echo hello
fi
$ ./testing 0 2
hello
$ ./testing 0 1
$ ./testing 1 1