The UNIX and Linux Forums  
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #4 (permalink)  
Old 02-03-2007
hegemaro hegemaro is offline
Registered User
  
 

Join Date: Feb 2006
Location: Schenectady, NY
Posts: 134
Arrow

zazzybob's solution is an elegant and simple solution.

In response to recursion within a Korn shell function, there are two points to consider. All variables, including the current working directory, are global unless specifically defined with the function which then makes them local within the function.
Code:
typeset FILENAME=/etc/hosts

Function ()
{
    FILENAME=/etc/resolv.conf
    echo $FILENAME
}

echo $FILENAME
Function
echo $FILENAME
would produce

/etc/hosts
/etc/resolv.conf
/etc/resolv.conf

However,

Code:
typeset FILENAME=/etc/hosts

Function ()
{
    typeset FILENAME

    FILENAME=/etc/resolv.conf
    echo $FILENAME
}

echo $FILENAME
Function
echo $FILENAME
would produce
/etc/hosts
/etc/resolv.conf
/etc/hosts

A quick and dirty way to make variables local to the function INCLUDING the working directory is to execute the function in its own shell by placing parenthesis within the function brackets. The function will get its own copy of the environment when called and any changes, including the directory, to that environment will not be reflected in the calling script which is its own function.

Code:
typeset FILENAME=/etc/hosts

Function ()
{ (
    FILENAME=/resolv.conf
    echo $FILENAME
) }

echo $FILENAME
Function
echo $FILENAME
would produce
/etc/hosts
/etc/resolv.conf
/etc/hosts

Last edited by hegemaro; 02-03-2007 at 10:41 AM..