本文介绍了重击后增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于在bash中执行Post-increment的正确方法只是一个小问题.

Just a little question about the right way of doing Post-increment in bash.

while true; do
  VAR=$((CONT++))
  echo "CONT: $CONT"
  sleep 1
done

在这种情况下,VAR从1开始.

VAR starts at 1 in this case.

CONT: 1
CONT: 2
CONT: 3

但是,如果我这样做:

while true; do
  echo "CONT: $((CONT++))"
  sleep 1
done

从0开始.

CONT: 0
CONT: 1
CONT: 2

似乎第一种情况是可以的,因为((CONT ++))会求值CONT(未定义,?0?)并加+1.

Seems that the the first case is behaving ok, because ((CONT++)) would evaluate CONT (undefined,¿0?) and add +1.

如何获得类似 echo 语句的行为来分配给变量?

How can I get a behaviour like in echo statement to assign to a variable?

在我的第一个示例中,我应该回显VAR,这样才可以正常工作,而不是回显CONT,所以从一开始就是我的错误.

In my first example, instead of echoing CONT, I should have echoed VAR, that way it works OK, so it was my error from the beginning.

推荐答案

两种情况都可以,而且合理.

foo ++ 将首先(自动递增之前)返回 foo 的当前值,然后自动递增.

foo++ will first return current value (before auto-incrementing) of foo, then auto-increment.

在第一种情况下,如果更改为 echo"CONT:$ VAR" ,它将得到与情况2相同的结果.

in your 1st case, if you change into echo "CONT: $VAR", it will give same result as case 2.

如果您想拥有 1,2,3 ... ,并且具有自动递增功能,则可以尝试:

If you want to have 1,2,3..., with auto-increment, you could try:

echo "CONT: $((++CONT))"

这篇关于重击后增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 21:58