【问题标题】:Incrementing in Bash shell script not showing the changed values? [duplicate]在 Bash shell 脚本中递增不显示更改的值? [复制]
【发布时间】:2019-01-21 11:35:45
【问题描述】:

我想增加一个变量,其值设置为23。每次递增后,它应该打印出新值,这是我的代码。

a=23
while [ $a -lt 45 ];


do  
$a =  `expr $a + 1` ; 
echo " the new value is $a "; 
done

但是我得到了这样的结果。

基本上它不会增加。

有人可以更正代码吗?

【问题讨论】:

  • 符合 POSIX 的 shell 中的变量赋值不会在变量名称前使用 $。你应该做a=$(expr "$a" + 1)

标签: bash shell scripting


【解决方案1】:

您在左赋值语句中使用了 $sign,这不是您所期望的。 请换行

$a =  `expr $a + 1` ; 

a=`expr $a + 1`;

还要注意= 符号前后的空格不应在 bash 脚本中使用

更新: 此代码在使用 bashsh 时不会出现语法错误:

a=23
while [ $a -lt 45 ]; do  
  a=`expr $a + 1` 
  echo "the new value is $a"
done

然后打印:

the new value is 24
the new value is 25
the new value is 26
the new value is 27
the new value is 28
the new value is 29
the new value is 30
the new value is 31
the new value is 32
the new value is 33
the new value is 34
the new value is 35
the new value is 36
the new value is 37
the new value is 38
the new value is 39
the new value is 40
the new value is 41
the new value is 42
the new value is 43
the new value is 44
the new value is 45

【讨论】:

  • 我做了上述更正,但我收到了一个新错误bash: [: missing ]' `
  • 是的,谢谢。
【解决方案2】:

您可以使用一种算术扩展

a=$((a+1))
((a=a+1))
((a+=1))
((a++))

另请阅读this guide

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-20
    • 2021-01-10
    • 2012-11-14
    • 2016-05-14
    • 2012-11-25
    • 2016-08-16
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多