0

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Alternate way:

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

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

echo $input
2

1 Comment

no need to call external expr. bash can do a bit of arithmetic on its own.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.