简体   繁体   English

在Shell脚本中的Math表达式中使用变量值

[英]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. 我正在尝试在循环内的另一个数学表达式中的FOR循环中使用迭代计数器的值。 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. 它已被弃用,并将在即将发布的Bash版本中删除。

Moreover, you can decrement with : 此外,您可以减少:

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

For more about calculation in Bash : 有关Bash中计算的更多信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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