variables in functions
I was going through a code and found that a variable declared within one function is being used from outside (another function as well).
Is it by default that the variable declared in a function is global. |
Hi -
I assume you're talking about shell scripts (in the future, it would probably be a good idea to specify the language and cut/paste some example code ... just to give everybody a clearer idea of what you're asking for). Yes, variables are indeed global in shell scripts (*unlike* most other languages, where variables are usually local by default). Here's an example: Code:
: Quote:
|
typeset can be used to make the scope of a variable local to a function. Consider the following script:
Code:
#!/bin/bash Code:
before testfn v1=variable1global |
Hi ,
Thanks for the help. I thought this forum for only unix based questions, so asked my question directly. Next time I will remember to specify the programming language. I have a follow on question on scripting.. is there a way to force the variable to be local in a function. Thanks |
Doesn't my previous post answer this already?
|
Actually, at the top of the forum it says
"Programming This forum is for all programming questions. The question does not have to be directly related to Linux and any language is fair game." ;) but don't worry about it, you know now. I think matthew42 has already answered your follow-up qn. |
Quote:
|
I think typeset is compatible with ksh which is probably where I picked it up (I don't think local is in ksh). Good to know there's a more readable keyword in bash. Thanks unspawn :D
|
All times are GMT -5. The time now is 02:16 PM. |