Mawnster
Mawnster

Reputation: 673

linux script simple arithmetic code

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?

Upvotes: 0

Views: 896

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 360055

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.

Upvotes: 0

Eddy
Eddy

Reputation: 1862

Alternate way:

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

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

echo $input
2

Upvotes: 3

jheddings
jheddings

Reputation: 27563

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.

Upvotes: 5

Related Questions