1

Google Style Guide says to always use local variables and put everything into function.

On the other hand sample for loop is provided:

for dir in ${dirs_to_cleanup}; do
  ...
done

Why there is no convention to always declare loop variable as local just before loop? Or maybe the following is the way how loops inside functions should be written to comply with the style guide?

local dir
for dir in ${dirs_to_cleanup}; do
  ...
done
Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
  • 4
    Style-guides are just that 'guides' (not decrees, mandates, proclamations, etc..) By declaring variables `local` to a scope you avoid name-collisions with variables of the same name elsewhere. Does that matter in a 20 line script, probably not. So they are more recommendations – David C. Rankin Feb 04 '19 at 09:53
  • 1
    `local` only makes sense in a function. What makes you think that the snippet you show is in a function? – gniourf_gniourf Feb 04 '19 at 11:24
  • And if the snippet were in a function, you might declare `local dir` at the top of that function, outside the "scope" of the sample. – Gem Taylor Feb 04 '19 at 11:32
  • @DavidC.Rankin my question is rather about long scripts in enterprise environment where consistency and style matters. Still, I see people declaring a lot of local variables in functions, but for some reason declaring `local` for loop variable is pretty uncommon in my environment, in the samples available on the internet and even in the style guide itself. Is there any reason for that? – Michal Kordas Feb 04 '19 at 11:56
  • @GemTaylor agreed, this is just small snippet where functions are not required, so local indeed wouldn't make sense – Michal Kordas Feb 04 '19 at 12:00

0 Answers0