| Date: Thu, 17 Feb 2011 12:41:43 -0000 (GMT)
| From: "Ciaran Johnston" <cj at nologic.org>
|
| Conor Wynne wrote:
| > When scripting in bash, and using C style syntax, example
| >
| > for (i=0;i<=50;i++)
| >
| > do I have to declare the variable(s) before hand?
|
| I take it you mean declare "i" beforehand? No.
However, the variable will be global (to the script).
*IF* this is inside a function, that may not be want
you want (and is arguably poor programming practice);
in that case, declaring it ‘local’ is advisable:
loop() {
local -i i
for ((i = 0; i <= 50; i++)) {
... do something ...
}
}
Also, if the type is supposed to be constrained (as
in this case) to an integer, declaring it as such
(‘-i’) can help catch borks. You can do that with
globals(to the script) with ‘declare’.
Incidentally, you can also use the sequence notation
for loops such as the above:
for i in {0..50}; do
... do something ...
done
I'm uncertain how much of the above is specific to
GNU bash(1), and how much is in POSIX. (Functions
are in POSIX.)
cheers!
-blf-
| The syntax is double
| brackets, not single brackets, unless I'm mistaken:
|
| for (( i = 0; i <= 50; i++ )) ; do
| echo $i
| done
--
“How many surrealists does it take to | Brian Foster
change a lightbulb? Three. One calms | somewhere in south of France
the warthog, and two fill the bathtub | Stop E$$o (ExxonMobil)!
with brightly-coloured machine tools.” | http://www.stopesso.com
Maintained by the ILUG website team. The aim of Linux.ie is to
support and help commercial and private users of Linux in Ireland. You can
display ILUG news in your own webpages, read backend
information to find out how. Networking services kindly provided by HEAnet, server kindly donated by
Dell. Linux is a trademark of Linus Torvalds,
used with permission. No penguins were harmed in the production or maintenance
of this highly praised website. Looking for the
Indian Linux Users' Group? Try here. If you've read all this and aren't a lawyer: you should be!