bashify.com
  • Home
  • Useful Techniques
  • Function Libraries
    • bashdb.shinc
    • datetime.shinc
    • defpath.shinc
    • die.shinc
    • getvar.shinc
    • ids.shinc
    • pathmunge.shinc
    • showvars.shinc
    • strings.shinc
    • timedkill.shinc
    • trace.shinc
    • trap.shinc
  • Scripts & Tools
  • Cool Tools
Sitemap
Print Version
Last update:
July 27. 2010 16:04:09
Login

Function Libraries

Sooner or later you will find yourself creating the same function, or at least a very similar version, over and over again. If you don't gather these utility-type functions into a library, then you'll eventually find that you have variances in your code that you are constantly stumbling over as you move between scripts.

For example, I have simple functions for ucase() and lcase(), as well as several other string manipulation functions, that I keep in a file strings.shinc. This means that anytime I need to upper or lower case a string, all I have to do is source in my library and use the functions.

What if I just wrote the function into the script?

lcase() {
    # usage: lcase < stdin
    /bin/tr '[A-Z]' '[a-z]'
}

That's easy enough to code, and we have a simple pipe for converting to lower case.

But what if later on in another script I code it like this:

lower() {
    # usage: lower string
    /bin/tr '[A-Z]' '[a-z]' <<<"$*"
}

That is also an acceptable way to code the function.

The problem is that as you move between scripts you'll have to remember which way you wrote the lower casing function. On the other hand, if you put these common (or sometimes not so common) snippets into a library, then you'll soon find yourself using them in predictable ways, just as you do the bash internal and external commands.

NOTE: The code provided here IS NOT warranted in any way. Feel free to use it, modify it, and otherwise abuse it -- but do so AT YOUR OWN RISK!

Submenu

  • bashdb.shinc
  • datetime.shinc
  • defpath.shinc
  • die.shinc
  • getvar.shinc
  • ids.shinc
  • pathmunge.shinc
  • showvars.shinc
  • strings.shinc
  • timedkill.shinc
  • trace.shinc
  • trap.shinc
<
TOP
>
Copyright © 2008 bashify.com — Powered by cmsimple.dk and cmsimple-styles.com