Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to reuse the same code at different point in a script 1

Status
Not open for further replies.
Jun 3, 2007
84
US
Hello,

I am not the best at scripting using shell scripts, plus I am a little rusty. I am trying to figure out how to reuse the same code at two different locations in a script. For those people that know Perl like a subroutine.

For example.

I am running some a check for the day of week (Mon, Tues...etc) if the day is Tuesday or Thursday then I want to run the same code at some point in the scripts if statement.

So I guess my question is if I am repeatedly using the same code but in two different places in a script, is there a way to only have the code populated only once but call it when needed. The way I have the script right now works just fine the only problem is that:

1) the size of the code is getting large
2) I am at some point in the script using the same exact code to do the same exact thing
3) code if going to get harder to read.

thanks for the help in advance, really appreciate it!!!!


example code
Code:
if [ $DAY == Tuesday ]
then
     running a regex to remove lines from a file
     then checking file size
     HERE IS WHERE I WOULD LIKE TO RUN ABOUT 10 LINES OF CODE
                      WHICH IS THE SAME EXACT CODE THAT I WILL USE IF
                                     THE DAY IS "Thursday"
fi

if [ $DAY == Thursday ]
then
      removing the files that end in a certain char
      making changes to the file using regex
      HERE IS WHERE I I AM USING THE SAME EXACT CODE AS ABOVE
                      WHICH IS THE SAME EXACT CODE THAT I WILL USE IF
                                     THE DAY IS "Tuesday"
fi
 
create a function.

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
In fact, if you have multiple choices like your sample, then you want to use a 'case' statement For example
Code:
#!/bin/ksh

process_data()
  {
  # This is the bit where the common work is done
  echo processing files for $1 #Note that $1 refers to the first param passed to the function
  }

case $DAY in
  Tuesday)
    #Do Tuesday specific stuff here
    process_data Tuesday
    ;; #End your case with a double semi colon
  Thursday)
    #Do Thursday specific stuff here
    process_data Thursday
    ;;
  *)
    #Default case - non Tuesday and Thursday stuff if required
    ;;
esac #End of case statement.

On the internet no one knows you're a dog

Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top