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. > > The following script seems to work just fine when using the "echo" command > instead of the currently used "printf" command. > > When using "printf", I get something like the following output on stdout: > > $ ~/bin/script.sh > CheckingDone > > > What I intend to get, and do get when using "echo" and omitting \n's is: > $ ~/bin/script.sh > Checking depedencies... > Done checking dependecies. > > > Is there any way to fix this so "printf" can be used instead of "echo"? > > Any additional ideas on performing this same task. (I'm always concerned > about wasting CPU cycles and code readability.) > > Using bash-4.2_p10 here. > > > ---begin snip--- > #!/bin/bash > DEBUG="1" > > # Function to optionally handle executing included debug statements > _debug() > { > # I prefer using if/then for readability, but this is an unusual case > [ "${DEBUG}" -ne "0" ] && $@ > } > > > _check_depends() > { > _debug printf "Checking depedencies...\n" > > # ...omit more additional scripting > > _debug printf "Done checking dependecies.\n\n" > } > > > # MAIN > _check_depends > > _debug echo "TEST for kicks" > > _debug printf "TEST for kicks\n" > ---end snip--- > > > > -- > Roger > http://rogerx.freeshell.org/ > >
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. 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). 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) -- Visit serverfault.com to get your system administration questions answered.