bash:变量内部的算术表达式

时间:2019-06-20 09:43:45

标签: bash loops variables equation

我有一个简单的代码,可以根据简单的算术等式在循环中分配变量

 # assign initial value
    restr_start='25'
    # assign a new variable, which is a number that will decrease initial value by 5
    # keeping always the value of previous variable as restr_prev 
    for step in {1..4}; do
      let "restr=(${restr_start} - (5 * ${step}))"
      let "restr_prev=(${restr} + (5 * ${step}))"
      echo this is $restr current restart
      echo this is $restr_prev previous restart
    done

我希望从此脚本中获得

this is 20 current restart
this is 25 previous restart
this is 15 current restart
this is 20 previous restart
this is 10 current restart
this is 15 previous restart
this is 5 current restart
this is 10 previous restart

无论我实际上拥有什么

this is 20 current restart
this is 25 previous restart
this is 15 current restart
this is 25 previous restart
this is 10 current restart
this is 25 previous restart
this is 5 current restart
this is 25 previous restart

为什么$ restr_prev通常不变?我如何修改代码,例如使用某些东西而不是

1 个答案:

答案 0 :(得分:2)

这是一个数学问题,而不是您的bash代码问题。查看$restr_prev的公式:

restr_prev= ${restr} + (5 * ${step})

对于步骤1,公式计算得出20 + 5 * 1 = 25,对于步骤2,公式得出15 + 5 * 2 = 25,依此类推...

为了获得您实际期望的结果,只需将5添加到restr值中。因此,脚本中的相应行应如下所示:

let "restr_prev=(${restr} + 5)"

正如注释中已经建议的那样,您应该使用$((expression))进行算术扩展,而不要使用let,因为后者是内置的bash,没有被POSIX standard覆盖。注意建议会导致以下代码:

#!/bin/bash

# assign initial value
restr_start='25'
# assign a new variable, which is a number that will decrease initial value by 5
# keeping always the value of previous variable as restr_prev 
for step in {1..4}; do
    restr=$((restr_start - (5 * step)))
    restr_prev=$((restr + 5))
    echo "this is $restr current restart"
    echo "this is $restr_prev previous restart"
done