23 Dec 2011 @ 8:00 PM 

A short one for today, then it’s week-end and I will only post on Tuesday (Monday is holiday).

In a script, one of the things which is usually overlooked is the validation of variables. And if you are developing a library of functions (for scripts), it is simply forgotten most of the times. This is one of the reason you are not re-using the functions made by your fellow developers : if you want them to work for your specific purpose, you have to specify a thousand of options that you will never use.

How can you make a function using optional variables (meaning that it will resort to default ones when nothing is specified) without writing dozens of lines of code ?

By using the little trick described in this article. This is how you define a default variable usually :

D_LOG_LEVEL=9

if [ “$1” = “” ]  #In case it is defined on the command line

then

LOG_LEVEL=${D_LOG_LEVEL}

else

LOG_LEVEL=$1

fi

 

Half your script went to write this wonderful code. Now, let’s make it faster.

First, we can replace the ifs with the one we’ve seen earlier this week :

 

D_LOG_LEVEL=9

([ “$1” = “” ] && LOG_LEVEL=${D_LOG_LEVEL}) || LOG_LEVEL=$1

Next step, we can get rid of the variable “D_LOG_LEVEL, as it is used only once.

([ “$1” = “” ] && LOG_LEVEL=9) || LOG_LEVEL=$1

Last step, let’s get rid of the not very nice “”=”” :

([ -z $1 ] && LOG_LEVEL=9) || LOG_LEVEL=$1

This allows you to define variable that are going to resort to default if it is not specified, without loosing too much time writing the code.

Note that if you define variables that need to be set before you send

([ -z ${LOG_LEVEL} ] && LOG_LEVEL=9)

Last thing about the variables in the function : You should test them before you run your function or script. This sounds obvious, but it is not usually the case (resulting is headache for people doing the support). If your script needs a filename as parameter and needs this file to exist, writing this line :

([ -z $1 ] || [ ! -f $1 ]) && (echo “File $1 Missing” && return 1)

is not going to take you much time and will help the next guy who is going to use your script.

Thank you for helping the Unix Scripting World to be a better place, and see you on Tuesday !

Posted By: Dimi
Last Edit: 23 Dec 2011 @ 04:02 PM

EmailPermalinkComments (0)
Tags

 Last 50 Posts
Change Theme...
  • Users » 66
  • Posts/Pages » 25
  • Comments » 4
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight