Reputation: 681
Re-asking this here, since it doesn't belong in the Code Review SE.
I was always taught to never have static expressions in code, as it is an unnecessary operation that will always have the same output. For example, you would never have if 6 < 7
(aside from people slapping the occasional while true
around).
That being said, I have a functioning bash script as follows:
#!/usr/bin/env bash
for i in {0..9}
do
...some stuff...
done
However, PyCharm is giving my hell for this re-iterating my concern in my first paragraph. It's counter suggestion is to have:
#!/usr/bin/env bash
for i in 0 1 2 3 4 5 6 7 8 9
do
...some stuff...
done
The logic is that it will not have to evaluate the range itself, thus increasing speed.
I think that the range looks nicer and, as far as I know, it won't actually affect speed (I don't mean noticeably, I mean at all), as it is simply iterating as it goes. Am I incorrect in thinking so?
It's a peeve of mine to waste cycles, but it's a greater peeve of mine to write grotesque looking code.
Upvotes: 0
Views: 43
Reputation: 295580
The best practice approach in bash or other shells adopting ksh extensions is a C-style for
loop:
for ((i=0; i<=9; i++)); do
echo "Doing some stuff with $i"
done
This has advantages over the {0..9}
syntax in that it works with variables ({$min..$max}
doesn't work, because brace expansions happens before variable expansions do) and avoids needing to store the full list in memory at once, and it has advantages over 0 1 2 3 4 5 6 7 8 9
because the latter is hard to check for typos (it's trickier to visually spot the problems with 0 1 2 3 5 4 6 7 8 9
or 0 1 2 3 4 6 7 8 9
).
Upvotes: 1