Scripting Best Practices
Treat Your Variables Right

Juliet Kemp
Tuesday, September 2, 2008 10:33:54 AM
Scripting languages are incredibly useful for quick-fix scripts. The
problem with this is when the quick-fix script is still in place 6 months down
the line, at which point the corners you cut because, hey, it's just a
short-term fix, come back to bite you. Read on for some best practice tips to
make the experience less painful.
(A note: my own scripting languages of choice are perl and bash, but the principles hold across other
languages.)
Treat your variables right
When you pass variables into a script or a subroutine, don't just
use the default names. Give them real names
immediately - it's much easier to keep track of what
you're passing in and what you're doing with it. A perl example:
sub concatenate_files {
my ($firstfile, $secondfile) = @_;
// rest of the subroutine
}
And while we're naming variables: name them something sensible.
Something that'll be meaningful when you read this, say, tomorrow morning
before coffee. So, $filelist, not $fl.
Don't hard-code anything. Put all your static values into variables, and
collect them all at the top of your script.
#!/bin/bash
EMAIL=admin@example.com
LOGFILE=/var/log/locallogs/mailscript.log
That way when something changes
(your email, the mailserver address) and the script breaks, the fix will be
a straightforward two-second job.
Next: Let Perl Help You »