我有以下脚本来递归清理目录,当它们不再包含(任何目录)任何.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
Run Code Online (Sandbox Code Playgroud)
这种方法很有效,除非在目录中有空格作为其名称的最后一个字符的情况下find失败,在这种情况下第二个失败,如果调用脚本,则返回以下反馈.作为唯一的参数,以及具有路径的目录'./FOO/BAR BAZ '(注意末尾的空格)存在:
find: `./FOO/BAR BAZ': No such file or directory
Run Code Online (Sandbox Code Playgroud)
(注意最后遗漏的空间,但其他空格保持不变.)
我很确定这是一个引用的东西,但我试过的其他引用方式会使行为变得更糟(即更多目录失败).
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.
Run Code Online (Sandbox Code Playgroud)
您可以设置IFS并避免单词拆分.说:
find -L "$1" -depth -type d | while IFS='' read dir
Run Code Online (Sandbox Code Playgroud)