11
Jun

Run Shell Script Subroutines in Terminal with Source Command

If you run a set of commands frequently, you might want to think about creating a sourced shell script with subroutines. For example, maybe you like to see the current date, a calendar, and a quick fortune (with the fortune package installed). Instead of typing cal and then date and then /usr/games/fortune -s manually each time, simply include it in a shell script that contains a subroutine that will do it all for you. All you need to do is create the script and subroutines and then source it like this:

. /my.subr

Notice the space between the period [.] and the script name. I usually use the .subr extension on my sourced scripts to tell them apart, but you can use whatever filename you want (it doesn’t even have to have an extension).

Then, simply call your subroutine within your shell script. Continuing with the example scenario described above, here is the shell script called my.subr that was sourced…

 
startmyday(){
   cal
   date
   echo
   /usr/games/fortune -s
}

anotherfunction(){
   echo "put whatever you want in this function call"
   echo "this is just a filler."
}

yetanotherfunction(){
   echo "put whatever you want in this function call"
   echo "this is yet another filler."
}

This is showing the sourced shell script subroutines in action…

# startday 
     June 2010      
Su Mo Tu We Th Fr Sa
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30         
                    
Fri Jun 11 04:17:56 UTC 2010

Do not drink coffee in early A.M.  It will keep you awake until noon.
# anotherfunction
put whatever you want in this function call
this is just a filler.
# yetanotherfunction
put whatever you want in this function call
this is yet another filler.
#

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 0 Comment So Far

Share your thoughts, leave a comment!