Bash - 如果文件夹有空格则脚本错误

Bash - Script error if folder with spaces

我有这个脚本

#!/bin/bash

rename_files() {
   title="${1##* - }"
   for filename in "/"*.*; do
   case "${filename##*.}" in
     doc|doc|doc)
       mkdir -p -m 777 "/Users/Desktop/Documents Share/Downloaded/${title}"
       new_path="/Users/Desktop/Documents Share/Downloaded/${title}/${title}.${filename##*.}"
       let "iters=1"
       while [ -f $new_path ] ; do
          new_path=$new_path"$iters"
          let "iters++"
       done
       echo "moving $filename -> $new_path"
       mv "${filename}" "${new_path}"
       ;;
   esac
   done
}

rename_category() {
  for path in "/Users/Desktop/Documents Share/Downloads/"*; do
    rename_files "$path" ""
  done
}

rename_category DOC

此脚本会自动移动和重命名 /Users/Desktop/Documents Share/Downloaded 中包含的文件。如果我使用名为 Documents 而不是 Documents Share 的文件夹,一切正常。我尝试使用 Documents\ Share 但它不起作用。

这是错误日志

/Users/Desktop/Script.sh: line 11: [: /Users/Desktop/Documents: binary operator expected

我该如何解决?

到处引用变量。指定行中缺少双引号:

while [ -f $new_path ] ; do

应该

while [ -f "$new_path" ] ; do

我认为 $new_path (第 11 行)应该用双引号引起来。