Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



Learning the bash Shell, 2nd Edition    (ISBN: 1565923472)


 

 List Price: $29.95
 Our Price: $20.97
 Used Price: $18.59

 Release Date: January, 1998
 Manufacturer: O'Reilly & Associates (Paperback)
 Sales Rank: 3,708

 Author: Cameron Newham, Bill Rosenblatt









More Info

 Functions 2002-09-03 23:08:35
  sh 
Category: source:sh:general
Description: Keep your code clean by including functions in your shell scripts.
Platform: unix
Author: mind
Viewed: 3441
Rating: 4.3/5 (6 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
function.sh
#!/bin/sh
#
# function_sh - mind (mind@metalshell.com)
#
# Basic example on the function structures
#
#       [ http://www.metalshell.com ]

# creating a function in a shellscript is quite usefull, say you had alot of
# variables and you wanted to all of them back to 0 but don't want to manualy
# set them all to 0 everytime you need to, Well to make it simpiler you can
# make a function to do it and everytime you need your variables set to 0 you
# can just call the function..

# Below are some examples on how to do functions and why they are useful
# a few examples will include while loops to show how useful a function
# can be..

reset_variables()
{
        # increase i by 1
        i=`expr $i + 1`

        # set our variable y back to 0
        y=0
}

append_test()
{
        # append message.. to our string
        str="$1 message.."
}

# define y and i as an integer of 0
y=0
i=0

# define z as an integer of 10
z=10

# define t as an integer of 3
t=3

# start our first function structure
echo "--- \"reset_variables()\" example ---"

while [ $i -ne $t ]
do
        if [ $y -eq $z ]
        then
                # call reset_variables
                reset_variables
        fi

        # increase y by 1
        y=`expr $y + 1`

        if [ $i -ne $t ]
        then
                # print our current position
                echo "On number $y of $z - Times looped: $i of $t"
        fi

done

# start our second function structure
str="test"

echo
echo "--- \"append_test()\" example ---"

echo "Our string before append_test(): $str"

# call append_test with $str as our first argument
append_test $str

# display results..
echo "Our string after append_test(): $str"
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?