views:

150

answers:

3

So I'm just working on some simple arithmetic code. Here's what I got:

echo "The number should be 2";

declare -i input added

input= date +%w

let added="input/2"

echo "$added"

when I run it the output is

4
0

I'm trying to just get 2. What the heck am I doing wrong?

+6  A: 

The problem is how you are creating the input variable. It is just executing the command, but not assigning the result to input. Instead, do:

input=$(date +%w)

This will assign the output of the date command to input.

jheddings
+3  A: 

Alternate way:

#Just echo the result:
expr $(date +%w) / 2

#store the result into a variable:
input=$(expr $(date +%w) / 2)

echo $input
2
Eddy
no need to call external expr. bash can do a bit of arithmetic on its own.
ghostdog74
A: 

One thing to note is that in Bash you generally can't have spaces around the equal sign.

An alternate syntax to using let is to use $(()) or (()):

var2=$((var1 / 2))

Or

((var2 = var1 / 2))

Inside the double parentheses, you can use spaces and you can omit the dollar sign from the beginning of variable names.

Dennis Williamson