0

当目录不再包含(任何目录)任何 .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

(注意最后缺少的空格,尽管其他空格保持不变。)

我很确定这是引用的事情,但是我尝试过的所有其他引用方式都会使行为变得更糟(即更多目录失败)。

4

1 回答 1

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
于 2013-10-30T05:43:48.250 回答