在执行时将bash命令打印到日志文件

时间:2016-06-08 20:18:34

标签: bash function command printf logfile

这是我到目前为止所拥有的:

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/

第一次调用exe,没有空格,就像我期望的那样工作。 第二次调用exe,它在路径中有一个空格,不起作用。

我试过在这个周围加上双引号,围绕着另一个东西,围绕着一切;我在空间之前尝试过反斜杠转义字符;我在空间之前尝试过双反斜杠。其中一些排列导致正确的行被打印到日志文件中,但其中包含空格的目录永远不会被删除。

帮助?

谢谢!

1 个答案:

答案 0 :(得分:2)

简短回答:见BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!

答案很长:当你在params中存储参数时,你会失去参数中的空格与参数之间的单词中断之间的区别。解决方案:改为使用数组,然后使用惯用语"${arrayname[@]}"引用它(双引号是关键的!),即使它包含空格,它也会将数组的每个元素转换为单个“单词”。明确地打印参数也有点棘手,但printf的%q格式可以做到。

这是我建议的重写(还有一些其他清理,比如删除=周围的空格):

# 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