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

Printing bash commands to a logfile as they execute

这是我目前的情况:

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/

对没有 spaces 的 exe 的第一次调用按我预期的方式工作。 第二次调用 exe,路径中有一个 space,不起作用。

我试过用双引号把这个、那个、另一个和所有东西都用双引号括起来;我在 space; 之前尝试了一个反斜杠转义字符;我在 space 之前尝试了双反斜杠。其中一些排列会导致将正确的行打印到日志文件中,但其中包含 space 的目录永远不会被删除。

帮忙?

谢谢!

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

长答案:当您将参数存储在 params 中时,您将失去参数内空格与参数间断字之间的区别。解决方案:改用数组,然后使用成语 "${arrayname[@]}"(双引号很重要!)引用它,这会将数组的每个元素转换为单个 "word",即使它包含空间。明确地打印参数也有点棘手,但 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