Why does bash ignore a '-' in a sequence brace expansion?
This yields all numbers between 1 and 10
echo {1..10}
This one yields all odd numbers between 1 and 10 (increment/step value is 2)
echo {1..10..2}
I experimented a bit, and it turned out if I prefix the increment by a -
sign, it has no effect
echo {1..10..-2}
Why is th开发者_StackOverflow中文版is accepted, rather than being an error?
From the bash(1)
man page:
When the increment is supplied, it is used as the difference between each term.
So... technically the output does have a difference of -2 between each term. But you still told it to increment rather than decrement in the sequence.
Experimentation with Bash 4.1 (as opposed to the 3.2 version installed by default on the machine I'm using, which does not recognize the notation as special) shows:
$ echo {12..10..2}
12 10
$ echo {12..10..-2}
12 10
$ echo {12..-10..2}
12 10 8 6 4 2 0 -2 -4 -6 -8 -10
$ echo {12..-10..-2}
12 10 8 6 4 2 0 -2 -4 -6 -8 -10
$ echo {-12..-10..-2}
-12 -10
$ echo {-12..-10..2}
-12 -10
$
So, it seems that the direction of the incrementing is controlled by the first two numbers; the magnitude of the incrementing is controlled by the third (defaulting to 1 if the third is missing).
精彩评论