Evaluating expressions

You can use expr utility to evaluate expressions in both of the command line or shell script.

Here are a few examples:

expr 6 + 4
10

Note the spaces. Without spaces, you get the following:

expr 6+4
6+4

If you are using “*” you will need a “” before it:

expr 10 \* 10
100

This also work for variables:

var1=2
var1=`expr $var1 \* 2`
echo $var1
4

You can get the cosine(.23):

var1=`echo "c(.23)" | bc -l`
echo $var1
.97366639500537483696

You can also do substrings:

expr substr "BigBear" 4 4
Bear

And length of strings:

mstr="12345"
expr length $mstr
5

Regular expressions:

expr "a3" : [a-z][1-9]
2

Or you can get a bit fancy:

myexpr="[a-z][1-9]"
expr "a3" : $myexpr
2

This may not be the best way to find out if it is Friday, but it seems to work. It’s more of an exercise in xargs.

date 
Fri Dec 31 16:44:47 EST 2004
date | xargs -i expr {} : "[Fri]"
1