DebianFanatic
DebianFanatic

Reputation: 53

Printing bash commands to a logfile as they execute

Here's what I have so far:

LOGFILE="/home/bubba/bubba.log"

# Function to echo commands to log file as they are executed
exe () {
  params = $@  #Put command-line into "params"
  printf "%s\%t\%s\n" "$params" >> $LOGFILE #Print date, a tab, and command to run
  $params  #Run the command-line
} #End of exe() function

exe rm -rf /usr/Library/bubbasfile.txt
exe rm -rf /usr/Library/bubbas add-ons/

The first call to exe, which has no spaces, works as I would expect it to work. The second call to exe, which has a space in the path, does not work.

I've tried putting double-quotes around this, and around that, and around the other thing, and around everything; I've tried a backslash escape character before the space; I've tried a double backslash before the space. Some of these permutations result in the correct line being printed to the log file, but the directory with the space in it never gets deleted.

Help?

Thanks!

Upvotes: 0

Views: 1042

Answers (1)

Gordon Davisson
Gordon Davisson

Reputation: 125728

Short answer: see BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!.

Long answer: when you store the arguments in params, you lose the distinction between spaces within arguments vs. word breaks between arguments. Solution: use an array instead, and then refer to it using the idiom "${arrayname[@]}" (double-quotes are critical!), which'll convert each element of the array into a single "word" even if it contains spaces. Printing the arguments to unambiguously is also a little tricky, but printf's %q format can do it.

Here's my suggested rewrite (with a few other cleanups, like removing spaces around the =):

# Function to echo commands to log file as they are executed
exe() {
  params=("$@")  # Put command-line into "params" as an array
  printf "%s\t%q" "$(date)" "${params[0]}" >> "$LOGFILE" # Print date, a tab, and the command name...
  printf " %q" "${params[@]:1}" >> "$LOGFILE" # then the arguments (with quotes/escapes as needed and spaces between)
  printf "\n" >> "$LOGFILE"
  "${params[@]}"  #Run the command-line
} # End of exe() function

Upvotes: 2

Related Questions