4

In ksh, I have two variables with the same name , one global , other one is local to a function

#!/bin/ksh

LOG_FILE=lf

function exec_script
{
   local LOG_FILE=f
   print $LOG_FILE
}
exec_script
print $LOG_FILE

If I want to refer the global variable $LOG_FILE within exec_script function, how should I qualify it so that the local does not get referenced ?

3
  • I bet you can't, but I don't know. Good question though. Sep 30 '13 at 15:20
  • Is acceptable for you to save global variable before the redefinition, like G_LOG_FILE=$LOG_FILE?
    – dchirikov
    Sep 30 '13 at 15:23
  • @dchirikov , Thank you. Currently I am using two seperate variables, prepending the local var name with a L.but I don't like it :). I am looking for something equivalent to a namespace or that sort as we have in C++.
    – user917279
    Sep 30 '13 at 15:44
1

I don't think that you can. I think it's a limitation of how Ksh interrogates the environment when looking for a variable's scoping.

excerpt from Scope of variables in KSH

Ksh has dynamic scoping, so the variable is also accessible in functions that are invoked by the function that declares the variable. This is tersely documented in the section on functions in the manual. Note that in AT&T ksh (as opposed to pdksh and derivatives, and the similar features of bash and zsh),

excerpt Parameters: An Overview

When you read or set a variable, zsh looks in the current function to see if that variable exists. If not, it looks in the next outermost function, and so on, until it reaches the global (outermost) scope. Therefore, if you assign a value to a variable that doesn't exist, the variable gets created in the outermost scope. (Exporting a new parameter also has this effect.)

5
  • Allow me to be dumb to ask this question, whatever ksh has , is it derived or adapted from zsh?
    – user917279
    Oct 1 '13 at 12:13
  • @user917279 - sorry for the confusion. I originally mis-read your question thinking it was asking about just Zsh. Here's additional details regarding Ksh as well.
    – slm
    Oct 1 '13 at 13:17
  • thank you. I went through that link before, stumbled on namespaces and compound variables, trying to figure out how could it solve my problem.
    – user917279
    Oct 1 '13 at 14:21
  • @user917279 - I think you're going to have to add logic to save your global variables to alternative names while in functions or use different names for the local variables. Not finding much in the way of methods to deal with this.
    – slm
    Oct 1 '13 at 15:11
  • Please remove the references to zsh. It is confusing given the OP.
    – Gray
    Feb 21 '18 at 21:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.