Hacker News new | past | comments | ask | show | jobs | submit login

For all you Bash heads out there:

  DRYRUN=1
  VERBOSE=1
  
  cmd() {
      [ $DRYRUN -eq 1 -o $VERBOSE -eq 1 ] \
          && echo -e "\033[0;33;40m# $(printf "'%s' " "$@")\033[0;0m" >&2
      if [ $DRYRUN -eq 0 ]; then
          "$@"
      fi
  }
And now you can put this all over your scripts to very easily implement dry-run behavior without any quoting worries. Note that you can't invoke aliases this way.

  cmd echo "don't worry about quoting"
  cmd do_something_dangerous "$scary_arg" "$scary_arg2"



Why not simply

  DRYRUN=echo
  
  cmd() {
    $DRYRUN "$@"
  }

?


The printf version will give you automatic quoting making copy'n'paste really easy to test. It' also mixes well w/ a verbose option for "--verbose" or such.


For those using zsh, you can get better quoting (and only when necessary, and handles non-printable characters and newlines better) than using printf.

run() { if dry; then echo "${(q-)@}" else "$@" fi }


I use this all the time (I call it $EXEC instead), and have gotten into the habit of starting all my scripts with EXEC=echo and put it on every command that does any file changes. It has saved my bacon many times.

It doesn't work all the time as the previous poster noted, but it is very low friction which is especially important when writing quick throw-away scripts.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: