为什么此脚本找不到名称以空格结尾的目录

时间:2013-10-30 05:33:21

标签: bash

我有以下脚本来递归清理目录,当它们不再包含(任何目录)任何.mp3或.ogg文件时:

  set -u
  find -L $1 -depth -type d | while read dir
  do
    songList=`find -L "$dir" -type f \( -iname '*.ogg' -o -iname '*.mp3' \)` && {
      if [[ -z "$songList" ]]
      then
        echo removing "$dir"
        rm -rf "$dir"
      fi
    }
  done

这很好用,除了在目录中有空格作为其名称的最后一个字符的情况下失败,在这种情况下第二个find失败,如果调用了脚本,则返回以下反馈与。作为唯一的参数,以及路径为'./FOO/BAR BAZ '的目录(注意末尾的空格)存在:

find: `./FOO/BAR BAZ': No such file or directory

(注意最后遗漏的空间,但其他空格保持不变。)

我很确定这是一个引用的东西,但我试过的其他引用方式会使行为变得更糟(即更多目录失败)。

1 个答案:

答案 0 :(得分:5)

read在遇到空格时分割输入。引用help read

Read a line from the standard input and split it into fields.

Reads a single line from the standard input, or from file descriptor FD
if the -u option is supplied.  The line is split into fields as with word
splitting, and the first word is assigned to the first NAME, the second
word to the second NAME, and so on, with any leftover words assigned to
the last NAME.  Only the characters found in $IFS are recognized as word
delimiters.

您可以设置IFS并避免单词拆分。说:

find -L "$1" -depth -type d | while IFS='' read dir