Bash - 如果带有空格的文件夹,脚本错误

时间:2016-03-19 12:10:34

标签: bash logging directory space names

我有这个脚本

#!/bin/bash

rename_files() {
   title="${1##*${2} - }"
   for filename in "$1/"*.*; 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/${1}"*; do
    rename_files "$path" "$1"
  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

我该如何解决?

2 个答案:

答案 0 :(得分:1)

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

Intent

shoudl be

while [ -f $new_path ] ; do

答案 1 :(得分:1)

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