Function ignoring global variables


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Function ignoring global variables
# 1  
Old 03-07-2010
Function ignoring global variables

Hi there.
I'm writing a function to which I want to pass a global variable. For some reason, it's ignoring the variable.

Code:
#!/bin/bash
#####################################
#Variable Declaration
#####################################

CURPATH=`dirname $0`
DEEP=$CURPATH/depth.txt

export $DEEP

function getdepth()
{

  echo $DEEP

  cat $1  | egrep ^${2} | awk -vgroup=$1 -vdepth=$DEEP -F, '
  {
      #Bunch of stuff that works when I hardcode it, but fails with the variable.

  }'
}


######
# Main block
######

getdepth some_file some_element

Any idea why the output of "echo $DEEP" is just a blank? And how do I make it pay attention to the global variables?

Thanks in advance,
Mike

---------- Post updated at 11:18 PM ---------- Previous update was at 11:14 PM ----------

Nevermind, I figured it out.

it's
Code:
export DEEP=$CURPATH/depth.txt.

Now I feel like a tool.
# 2  
Old 03-07-2010
Quote:
Originally Posted by mikesimone
Hi there.
I'm writing a function to which I want to pass a global variable. For some reason, it's ignoring the variable.

Code:
#!/bin/bash
#####################################
#Variable Declaration
#####################################

CURPATH=`dirname $0`


There's no need to use dirname in bash (or any POSIX shell); use parameter expansion:
Code:
CURPATH=${0##*/}

(But there's rarely a good reason to require the location of the script.)
Quote:
Code:
DEEP=$CURPATH/depth.txt

export $DEEP


Code:
export DEEP

Why are you exporting DEEP? Are you calling another script that will need it?
Quote:
Code:
function getdepth()


That is a bash hybrid, a combination of ksh syntax and standard syntax. Use standard syntax:
Code:
getdepth()

Quote:
Code:
{

  echo $DEEP

  cat $1  | egrep ^${2} | awk -vgroup=$1 -vdepth=$DEEP -F, '


UUOC
Quote:
Code:
  {
      #Bunch of stuff that works when I hardcode it, but fails with the variable.


What "stuff"? If that's where it fails, that's what you should be posting.
Quote:
Code:
  }'
}


######
# Main block
######

getdepth some_file some_element

Any idea why the output of "echo $DEEP" is just a blank? And how do I make it pay attention to the global variables?

Thanks in advance,
Mike

---------- Post updated at 11:18 PM ---------- Previous update was at 11:14 PM ----------

Nevermind, I figured it out.

it's
Code:
export DEEP=$CURPATH/depth.txt.

Now I feel like a tool.
# 3  
Old 03-07-2010
Thank you kindly for your help. I'll make the changes to my syntax that you describe. However, to answer some of your concerns:


Quote:
Originally Posted by cfajohnson
[indent]
There's no need to use dirname in bash (or any POSIX shell); use parameter expansion:
[/code]
I have that in there for now, because I originally had several scripts being called, instead of knowing how to get them all as functions in one script, and I wanted to make sure I had an easy way to change all of their paths if I needed to.

[QUOTE=cfajohnson;302401579][indent]

Code:
export DEEP

Why are you exporting DEEP? Are you calling another script that will need it?
Because until I exported it, this function flatly refused to believe its existence - hence the subject of the post. It would always return a blank.

Quote:
Originally Posted by cfajohnson
[indent]

What "stuff"? If that's where it fails, that's what you should be posting.
The only line of importance, really, was the "echo $DEEP", since, if $DEEP had no value (which was the problem I was experiencing), then the rest of the stuff would fail, but if $DEEP had a value, it worked.

Once I made the change that I posted (export DEEP=blahblahblah), it worked magic.

If you really want to view a bunch of cringe-worthy code, I'll be happy to PM you the whole sad script, but, the reality is, I'm just trying to slam a hodge-podge of what little I know about bash scripting into a workable tool that will take the useless output from the configuration reports of a SYMC firewall and convert it into Cisco commands. I'm a network guy - once it gets past layer four, I stop caring. Smilie
# 4  
Old 03-07-2010
Quote:
Originally Posted by mikesimone
Quote:
Originally Posted by cfajohnson
[indent]

Code:
export DEEP

Why are you exporting DEEP? Are you calling another script that will need it?
Because until I exported it, this function flatly refused to believe its existence - hence the subject of the post. It would always return a blank.

Exporting DEEP makes no difference in the code you posted. The problem is elsewhere.
# 5  
Old 03-07-2010
Data

Quote:
Originally Posted by cfajohnson

Exporting DEEP makes no difference in the code you posted. The problem is elsewhere.
Perhaps it should not make a difference, but the fact is that when I export it, it works, and when I don't, it doesn't. However, I'll post my whole horribly awful file here, and perhaps you'll see why it doesn't work when it's not exported. The root cause of all of my scripting woes is, of course, "I suck at scripting, and am only doing this to keep from trying to create 2000 objects by hand", instead of "gosh, I really love this stuff, and want to do it right."

It truly is an awful hodge-podge. Don't say I didn't warn you.

Try not to puke into your keyboard when/if you read it.

Code:
#!/bin/bash



#####################################
#Variable Declaration
#####################################

CURPATH=`dirname $0`
CSV=$CURPATH/output.csv
CISCO=$CURPATH/cisco_protocol_object_groups.txt
PROTOCOLS=$CURPATH/protocol_table.csv
GROUP=$CURPATH/groups.csv
ERRORS=$CURPATH/ambiguous_group_members.txt
FTEMP=$CURPATH/swap.txt
export DEEP=$CURPATH/depth.txt





##############################################################
# Declare Functions
##############################################################
function getdepth()
{
  ## ARGUMENTS:
  # $1 is the groups file from which we obtain the member list
  # $2 is the group name whose members we're querying


  cat $1  | egrep ^${2} | awk -vgroup=$1 -vdepth=$DEEP -F, '
  {
      for (i=2;i<=NF;i++)
          {
           if ($1 != "") 
           {
            if (system("isgroup " group " "  $i) != 0)
            {
                {system("echo " group " is being sent to " depth) 2>/dev/null}
                {system("setdepth " $i " " depth ) 2>/dev/null}
                {system("getdepth " group " " $i) 2>/dev/null}

            }
          }

    }
  }'
}



function setdepth()
{
    #ARGUMENTS:
    # $1 is the element for which we are searching.
    # $2 is the depthfile from which we're running the search
    echo $1 $2
    if [ ! -f $2 ]; 
       then touch $2  
    fi
    
    let DEPTH=`cat $2 | egrep ^${1} | cut -d: -f2`+1
    cat $2 | egrep -v $1 > tmp
    echo ${1}:${DEPTH} >> tmp
    sort -t: -rnk 2,2 tmp >$2
    rm -f tmp
}

function isgroup()
{
  #ARGUMENTS:
  #$1 is the name of the groups file
  #$2 is the group name we seek.
  
  excode=`cat $1 | egrep -wc ^${2}`
  exit $excode
}

function protocolshred()
{
    echo -e "Processing" $1


    echo -e "Stripping HTML tags"
    tr -d '\t' < $1 | sed 's/<.*>//g' | sed '/^$/d' | sed 's/\&amp\;/,/g' | egrep -v "Symantec Gateway Security|Report Generated|Network Protocol Report|UUID|Caption|Description|Read only|true|false" | sed 's/Base Protocol/\nBase Protocol/g' > $CSV
    #Next, fix the stuff with weirdly placed line breaks
    echo -e "Removing erroneously placed line breaks"
    perl ./fixit.pl $CSV
    #Turn it into a nice CSV file where most of the columns line up.
    echo -e "Converting to CSV"
    cat $CSV | egrep -v "[A-F0-9]{8}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{12}|Use Native Service|Use GSP"  |  tr '\n' ',' | sed 's/,,/,/g'|  perl -pe 's/,Protocol name:/\nProtocol name:/g' | sed 's/Protocol name: //g' | sed 's/-,/-/g'  > $FTEMP
    #Remove my temp file
    rm -f $CSV
    mv $FTEMP $CSV
    echo -e "Removing comments and other unhelpful items."
    #Remove comments to make the rest of the columns line up properly.
    cat $CSV | awk -F, '
        {for (i=1;i<=NF;i++)
           {
             if (((i < 4) || ($i ~ /(Native Service|(Source|Destination) (High|Low)) Port/) || ($i ~ /^[0-9]+$/)) && (i != NF))
                {printf $i ",";}
             else if (i == NF)
             {printf $i "\n"};
           }

        }' > $PROTOCOLS

    #Ahhh. Many perfect little lines. Everything in the same column.
    #Don't need this $CSV file anymore
    rm -f $CSV
}

function groupshred()
{
   echo -e "Processing" $1
   #First, rip out the OBVIOUS trash
    echo -e "Stripping HTML tags"
    tr -d '\t' < $1 | sed 's/<.*>//g' | sed 's/\&[gl]t\;//g' | sed '/^$/d' | sed 's/\&amp\;/,/g' | egrep -v "Symantec Gateway Security|Report Generated|Service Group Report|UUID|Caption|Description|Read only|true|false" | sed 's/Service Group Name:/\nService Group Name:/g' > $CSV

    #Next, fix the stuff with weirdly placed line breaks
    echo -e "Removing erroneously placed line breaks"
    perl ./fixit.pl $CSV

    #Turn it into a nice CSV file where most of the columns line up.
    echo -e "Converting to CSV"
    cat $CSV | sed 's/Additional/\nAdditional/g'|  egrep -v "[A-F0-9]{8}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{12}"  |  tr '\n' ',' |sed 's/[ \t]*$//' | sed 's/,,/,/g'|  perl -pe 's/,Service Group Name:/\nService Group Name:/g' | sed 's/Service Group Name: //g' | sed 's/-,/-/g' | sed '/^$/d' > $FTEMP
    #Remove my temp file
    rm -f $CSV
    mv $FTEMP $CSV


    #Yank out the descriptions
    cat $CSV | awk -F, '
        {
         {pf = 0}
         for (i=1;i<=NF;i++)
             {if ($i ~ /^Protocols$/) {pf = (i+1)}}
         printf $1 ","
         for (i=pf;i<=NF;i++)
             {
              if (i == NF) {print $i;}
              else {printf $i ","};
             }
          }
     ' > $GROUP

    #Aaaaaand, wipe out the temp table
    rm -f $CSV
}

function NestedGroups()
{
  echo "Finding nested groups."

   cat $GROUP | awk -F, -v groupfile=$GROUP '
       {if ($1 != "")
       {system("getdepth " groupfile " " $1) 2>/dev/null} }'
}


###############################################
# Cleanup
###############################################
function cleanup()
{
    files="$CSV $HNS $PIVOT $GROUP $ERRORS $FTEMP $DOMAINS $NAMES $LOCATIONS $DEEP"
    # $i will hold single file at a time in following loop
    for i in $files
    do
       if [ -f $i ]; then
         echo -e "Deleting file from last run: " $i
         rm -f $i
       fi
    done
}


############################################################
# Export Functions
############################################################
export -f getdepth
export -f setdepth
export -f isgroup


###############################################
# Check for proper number of command line args.
###############################################

EXPECTED_ARGS=2
E_BADARGS=65

if [ $# -ne $EXPECTED_ARGS ]
then
  echo "Usage: `basename $0` /path/to/Protocols.htm  /path/to/Service_Groups.htm"
  exit $E_BADARGS
fi



###########################################################
# MAIN BODY
##########################################################

###
# Ran it before, and need to clean up the old files?
###

   cleanup


##
# Send the protocols file for processing
##

  protocolshred $1

##
# Now we start processing the groups list.#
##

  groupshred $2

###
# The first step in processing the groups is to figure out which ones to do first.
# The ones that are nested deepest must be created in the ASA before the ones that
# contain them, or there's going to be an error. I don't like errors.
###


   NestedGroups

###
# Holy shit, it worked. That little bit you saw was two days of work. God, I suck at programming.
# Anyway, now that we know which groups to define first, we can start the relatively simple process
# of populating the groups.
###

#Haven't written this part yet, but it should be fairly straightforward.

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Global variables in perl

hi all, i need a help for the following query. Thanks in advance for your valuable time. i have a main.pl file which has a global variable declared as below. our myVar=0; call first.pl script from the main.pl script. print the value of myVar (the value is still 0 and not 10.) i have a... (1 Reply)
Discussion started by: hemalathak10
1 Replies

2. Shell Programming and Scripting

Find global variables, c source

Hello.I have been trying to solve the following problem, but to no avail. If anyone could please give me some indications, or anything, it would be amazing. A C source program and a type name are given. Determine from source, the list of the global variables having the given type. For each... (5 Replies)
Discussion started by: Susan78
5 Replies

3. Solaris

How to access ENV variables of non global zones in global zone???

Hi Guys, My requirement is I have file called /opt/orahome/.profile in non global zone. PATH=/usr/bin:/usr/ucb:/etc:/usr/sbin:/usr/local/bin:/usr/openwin/bin:. export PATH PS1="\${ORACLE_SID}:`hostname`:\$PWD$ " export PS1 EDITOR=vi export EDITOR ENV=/opt/orahome/.kshrc export ENV... (1 Reply)
Discussion started by: vijaysachin
1 Replies

4. Programming

global variables and dynamic allocation

Hi, is it possible in C to allocate dynamically a global variable?? (3 Replies)
Discussion started by: littleboyblu
3 Replies

5. UNIX for Dummies Questions & Answers

global variables

Hi, I hav created a script that calls a sub-script. In both the scripts i called the configuration file. Now i wanted to use a variable that should be used in both script and sub-script files. Actually, i wanted to return a file name and the return status to the script file from the sub-script.... (6 Replies)
Discussion started by: Swapna173
6 Replies

6. Shell Programming and Scripting

Passing global variable to a function which is called by another function

Hi , I have three funcions f1, f2 and f3 . f1 calls f2 and f2 calls f3 . I have a global variable "period" which i want to pass to f3 . Can i pass the variable directly in the definition of f3 ? Pls help . sars (4 Replies)
Discussion started by: sars
4 Replies

7. Shell Programming and Scripting

Problem with global and local variables

Guys, how can I define global variables in sorlaris...cause I lose the values outside the scope. Rite now wat I do is,I redirect variable value to a file n then get it back outside the function...:o....theres obviously a better way of doing this...I now this is a basic question....but please... (2 Replies)
Discussion started by: qzv2jm
2 Replies

8. BSD

Declaring Global Variables in KLD

Hello, how can I define a global variables in KLD? I would like to define some variables in my KLD and then would like to use them from other KLD. Thanx (1 Reply)
Discussion started by: int80h
1 Replies

9. Programming

global variables in KLD (FreeBSD)

Hello dear BSD hackers, how can I define and then make visible some variables that I define in KLD (BSD) for other part of Kernel or other KLD's ? if i declare for example the varibale out of load-function of KLD , the name of this variable isn't export to symbol-table and the variable can... (0 Replies)
Discussion started by: int80h
0 Replies

10. Shell Programming and Scripting

perl global variables

Can someone give me "the lecture" on why you shouldn't make all your varables global when programming in perl. I have been doing this but I have heard that it is not a good practice. (3 Replies)
Discussion started by: reggiej
3 Replies
Login or Register to Ask a Question