Reputation: 3233
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.
Upvotes: 0
Views: 387
Reputation: 15461
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/
Upvotes: 2
Reputation: 1308
Try this:
for i in {100..1}
do
j=$(($i-1)) <- Here is the change.
echo $i $j
done
Upvotes: 3