简体   繁体   中英

Use variable value in a Math expression in Shell Scripting

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.

Try this:

for i in {100..1}
do
    j=$(($i-1))  <- Here is the change.
    echo $i $j
done

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM