0

I am trying to use the value of the iteration counter in a FOR loop in another mathematical expression inside the loop. Example code:

#! /bin/bash

for i in {100..1}
do
    j=$($i-1)
    echo $i $j
done

However, this does not work. I want to get the output as shown below:

100 99
99 98

and so on.

2 Answers 2

3

Try this:

for i in {100..1}
do
    j=$(($i-1))  <- Here is the change.
    echo $i $j
done
Sign up to request clarification or add additional context in comments.

Comments

2

You have to double parenthesis :

j=$(( $i-1 ))

or :

j=$(( i-1 ))

This syntax works :

$[ $i-1 ] 

But you shoud avoid it. It's deprecated and will be removed in upcoming versions of Bash.

Moreover, you can decrement with :

j=i
echo $i $(( --j ))

For more about calculation in Bash :

https://www.shell-tips.com/2010/06/14/performing-math-calculation-in-bash/

2 Comments

or just not use j at all as it is redundant and is always 1 less than i, just print i-1
You're right, It doesn't make a lot of sense, it's just to cover all syntax.

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.