![Bash 변수 증분, 일관되지 않은 동작](https://rvso.com/image/168827/Bash%20%EB%B3%80%EC%88%98%20%EC%A6%9D%EB%B6%84%2C%20%EC%9D%BC%EA%B4%80%EB%90%98%EC%A7%80%20%EC%95%8A%EC%9D%80%20%EB%8F%99%EC%9E%91.png)
나는 이것이 (단순한 버그라기보다는) 의도적인 것이라고 생각합니다. 그렇다면 정당화를 위해 관련 문서를 안내해 주세요.
~$ i=0; ((i++)) && echo true || echo false
false
~$ i=1; ((i++)) && echo true || echo false
true
두 줄의 유일한 차이점은 i=0
vs 입니다 i=1
.
답변1
그렇기 때문에 i++
그렇습니다
사후 증분에 설명된 대로 man bash
. 즉, 표현식의 값은 다음과 같습니다.원래의i
증가된 값이 아닌 의 값 입니다.
ARITHMETIC EVALUATION
The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and
declare builtin commands and Arithmetic Expansion). Evaluation is done in fixed-width integers with no
check for overflow, though division by 0 is trapped and flagged as an error. The operators and their prece-
dence, associativity, and values are the same as in the C language. The following list of operators is
grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence.
id++ id--
variable post-increment and post-decrement
하도록 하다:
i=0; ((i++)) && echo true || echo false
다음과 같이 행동합니다:
i=0; ((0)) && echo true || echo false
i
그것도 증가한다는 점을 제외하면 ; 그리고 그것은:
i=1; ((i++)) && echo true || echo false
다음과 같이 행동합니다:
i=1; ((1)) && echo true || echo false
i
그것도 증가한다는 점을 제외하면 .
값이 0이 아닌 경우 구성 의 반환 값 (( ))
은 진실( )이고 그 반대의 경우도 마찬가지입니다.0
사후 증가 연산자가 어떻게 작동하는지 테스트할 수도 있습니다.
$ i=0
$ echo $((i++))
0
$ echo $i
1
그리고 비교를 위한 사전 증분:
$ i=0
$ echo $((++i))
1
$ echo $i
1
답변2
]# i=0; ((i++)) && echo true || echo false
false
]# i=0; ((++i)) && echo true || echo false
true
an의 '반환' 값은 ((expression))
접두어 또는 접미어에 따라 달라집니다. 그리고 논리는 다음과 같습니다.
((expression))
The expression is evaluated according to the rules described be low under ARITHMETIC EVALUATION.
If the value of the expression is non-zero,
the return status is 0;
otherwise the return status is 1.
이는 반환 값과 달리 정상으로 바뀌는 것을 의미합니다.