views:

74

answers:

5

I am building a movie database and I need to find a median for ratings. I'm really new to bash (it's my first assignment).

I wrote:

let evencheck=$"(($Amount_of_movies-$Amount_of_0_movies)%2)"
if [ $evencheck==0 ] 
then
let median="(($Amount_of_movies-$Amount_of_0_movies)/2)"
else
let median="(($Amount_of_movies-$Amount_of_0_movies)/2)+1"
fi

When $amount_of_movies = 6 and $amount_of_0_movies = 1. I would expect median to be 3. but it's 2. Why is that?

A: 

try this in your if test:

[ "$evencheck" == 0 ]
ennuikiller
It worked! genius :)thank you very much, all of you.
Gal
Accept the answer...
Eton B.
A: 

Does median have some sort of default value? The way I see it, it's not even going inside the if.

(6-1) % 2
5 % 2
1, not 0
Eton B.
+1  A: 

try this:

let evencheck="(($Amount_of_movies-$Amount_of_0_movies)%2)"
if [ $evencheck -eq 0  ] 
then
   let median="(($Amount_of_movies-$Amount_of_0_movies)/2)"
else
   let median="(($Amount_of_movies-$Amount_of_0_movies)/2)+1"
fi

Removing the $, and then testing for numeric equality.

Doon
A: 

Your code doesn't parse. To evaluate expressions in Bash, you say

let evencheck="$((($Amount_of_movies-$Amount_of_0_movies)%2))"

That is, evaluate arithmetics like so: $(( ... ))

That said, your problem is in the conditional. See man test.

if [ $evencheck = 0 ]; then

You have to wrap the equality sign with whitespace on both sides. Use a single equality sign.

wilhelmtell
A: 

The outermost parentheses and none of the quotes are necessary in what you've got (they may be in other circumstances). Also, in a let statement you can omit the dollar sign from variable names.

let evencheck=(Amount_of_movies-Amount_of_0_movies)%2
if [ $evencheck == 0 ]  
then
    let median=(Amount_of_movies-Amount_of_0_movies)/2
else
    let median=(Amount_of_movies-Amount_of_0_movies)/2+1
fi

If you use the (()) form instead of let, you can uses spaces to make your formulas more readable. You can also use them in if statements:

(( evencheck = ( Amount_of_movies - Amount_of_0_movies ) % 2 ))
if (( evencheck == 0 ))
then
    (( median = ( Amount_of_movies - Amount_of_0_movies ) / 2 ))
else
    (( median = ( Amount_of_movies - Amount_of_0_movies ) / 2 + 1 ))
fi
Dennis Williamson