views:

100

answers:

7
echo 3+3

How can I evaluate such expressions in Bash, in this case to 6?

+1  A: 

Lots of ways - most portable is to use the expr command:

expr 3 + 3
anon
+7  A: 
echo $(( 3+3 ))
Marcelo Cantos
A: 

Use can make use of the expr command as:

expr 3 + 3

To store the result into a variable you can do:

sum=$(expr 3 + 3)

or

sum=`expr 3 + 3`
codaddict
+4  A: 

expr is the standard way, but it only handles integers.

bash has a couple of extensions, which only handle integers as well:

$((3+3))  returns 6
((3+3))   used in conditionals, returns 0 for true (non-zero) and 1 for false
let 3+3   same as (( ))

let and (( )) can be used to assign values, e.g.

let a=3+3
((a=3+3))

for floating point you can use bc

echo 3+3 | bc

Dan Andreatta
+2  A: 

in shells such as zsh/ksh, you can use floats for maths. If you need more maths power, use tools like bc/awk/dc

eg

var=$(echo "scale=2;3.4+43.1" | bc)
var=$(awk 'BEGIN{print 3.4*43.1}')

looking at what you are trying to do

awk '{printf "%.2f\n",$0/59.5}' ball_dropping_times >bull_velocities
ghostdog74
Elegant, thank you.
HH
any idea about a comment sign for AWk? If I want to have an explicitly stated format for my measurements? Reading just columns can be confusing.
HH
i don't understand. show what you mean by examples in your question
ghostdog74
@Heoa: AWK uses "#" for comments, like many others.
Dennis Williamson
A: 

Solved thanks to Dennis, an example of BC-use:

$ cat calc_velo.sh

#!/bin/bash

for i in `cat ball_dropping_times`
do
echo "scale=20; $i / 59.5" | bc 
done > ball_velocities
HH
put this into your question. also, you can just use one awk command. It parses files, and takes care of decimal maths. see my answer.
ghostdog74
You're using the redirect operator `>` which truncates (overwrites) the destination file each time. Change that to the append operator `>>` or put the redirection after the `done` instead of after the `bc` like this: `done > ball_velocities`.
Dennis Williamson
A: 

I believe the ((3+3)) method is the most rapid as it's interpreted by the shell rather than an external binary. time a large loop using all suggested methods for the most efficient.

The HCD