Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In shell script we can substitute expr $a*$b with $(($a+$b)).

But why not just with (($a+$b)), because in any resource it is written that (()) is for integer computation.

So we use $(()) when there are variables instead of integer values do we? And what should we use instead of $(()) when variables can receive float values?

share|improve this question
    
up vote 8 down vote accepted
  1. expr is archaic. Don't use it.

  2. $((...)) and ((...)) are very similar. Both do only integer calculations. The difference is that $((...)) returns the result of the calculation and ((...)) does not. Thus $((...)) is useful in echo statements:

    $ a=2; b=3; echo $((a*b))
    6
    

    ((...)) is useful when you want to assign a variable or set an exit code:

    $ a=3; b=3; ((a==b)) && echo yes
    yes
    
  3. If you want floating point calculations, use bc or awk:

    $ echo '4.7/3.14' | bc -l
    1.49681528662420382165
    
    $ awk 'BEGIN{print 4.7/3.14}'
    1.49682
    
share|improve this answer
1  
If expr is archaic what should we use instead of expr text : '.*' – Stranger 2 days ago
    
If s is a shell variable, its length is ${#s} – John1024 2 days ago
    
${#} means a number of arguments and $(#s} means a number of characters of a variable does it? – Stranger 2 days ago
    
Yes. That's right. – John1024 2 days ago
1  
@Stranger Many uses of expr STRING : REGEX can be written as case STRING in PATTERN). expr is only useful when REGEX can't be expressed with shell wildcards. – Gilles yesterday

expr is old, but it does have one limited use I can think of. Say you want to search a string. If you want to stay POSIX with grep, you need to use a pipe:

if echo november | grep nov 
then
  : do something
fi

expr can do this without a pipe:

if expr november : nov
then
  : do something
fi

the only catch is expr works with anchored strings, so if you want to match after the beginning you need to change the REGEXP:

if expr november : '.*ber'
then
  : do something
fi

Regarding (( )), this construct is not POSIX, so should be avoided.

Regarding $(( )), you do not have to include the dollar sign:

$ fo=1
$ go=2
$ echo $((fo + go))
3
share|improve this answer
1  
Many uses of expr STRING : REGEX can be written as case STRING in PATTERN). expr is only useful when REGEX can't be expressed with shell wildcards. – Gilles yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.