> On Mon, Aug 08, 2011 at 08:56:36AM -0500, Dennis Williamson wrote: >On Mon, Aug 8, 2011 at 3:47 AM, Roger <rogerx....@gmail.com> wrote: >> I'm doing some research for one of my scripts and always liked the C style >> ifdef inline debug statements.
... >Another way to write the _debug() function: > >#!/bin/bash >debug=true > ># Function to optionally handle executing included debug statements >_debug() >{ > debug && "$@" >} > >Using this method, you don't really need a function at all. You can >just use the debug variable directly (you could use an underscore >prefix): > > $debug && printf "Checking depedencies...\n" > > $debug && { > # it's even more like ifdef since you can conditionally >execute blocks of code > foo > bar > } > >You have to make sure that $debug contains only "true" or "false" or >you'll get errors. There are exceptions to this, but the complexity >isn't worth the effort. This is interesting because I'm guessing it might save one or two CPU cycles, although it still does use a test at "&&", and is still readable, if not more readable then before. >I prefer using lowercase or mixed case variable names by habit to >reduce the chances of name collisions with predefined variables >(although that's not an issue with this specific script). I know the system capitalized defined variables, so I usually just use all capitalized variable for global script variables within the header/top of the bash script. I've heard of the risk of collision, and have tried mixed-case variable names, but they were not as readable and the risk seemed more minimal ... unless a Linux distribution makes up a system variable that conflicts with one of my all capitalized variable names. I then use lower case for locally used variables within the Bash script or within the functions of the script. Similar to C. It just makes good sense, and I know where to look for predefined capitalized variable names for their definition. >Since you're writing a script for Bash, you might as well use Bash >features. Here is the main line of your function a couple of more >different ways (using the original capitalization and value): > > [[ $DEBUG != 0 ]] && "$@" # string comparison > (( DEBUG != 0 )) && "$@" # integer comparison (note, >the $ is unnecessary) Yup. I was thinking of sticking with 0's & 1's, as text comparison requires more CPU cycles ... although negligible these days, it's just good programming practice. -- Roger http://rogerx.freeshell.org/