'Bash operator ++ behavior weired with a constant
By occasionally, I meet a problem when calculating a self-increment operation ++ with a constant, the behavior is weird for me (this is not the original code, I just copied the looks-like lines).
#!/bin/bash
echo "out1="$((++5))
echo "out2="$((5++))
The code snippet looks like about; when I execute it, I got following result:
$ bash test.sh
out1=5
test.sh: line 3: 5++: syntax error: operand expected (error token is "+")
The bash version is: GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
I want to know:
- why there is no syntax error for pre-increment operator ?
- why the post-increment operate return a value 5, other than 6.
Thanks.
Solution 1:[1]
I can't say for sure, I don't feel like browsing the source to learn about the arithmetic expression parser. My guess is:
- pre-increment is not actually preincrement, but that you can put any number of
+and-symbols before a constant to determine if it's positive or negative. I suspect the parser is seeing$(( +(+5) ))- summary: you're just specifying the number's sign.
- as post-incrementing a constant makes no sense (you can't assign the constant 5 with the value 6), it is taken as if you were typing "5 plus ... something" and instead of an arithmetic value you gave another plus sign. So, syntax error, and "operand error" message. Like the parser is seeing
$(( (5) + (+) ))- summary: the first plus is OK, the second is an error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | glenn jackman |
