处理包含数组中空格的文件和目录列表

时间:2012-09-27 18:22:45

标签: macos bash

如何最好地处理数组中的文件和目录组合。我需要创建一个文件和文件夹数组并循环遍历数组,并使用-rf选项将数组中的每个项目放到rm命令中:

#Build array of files to be deleted

FILES=(
"~/Library/Preferences/Adobe InDesign"
"~/Library/Caches/Adobe InDesign"
"~/Library/Saved Application State/com.adobe.InDesign.savedstate"
)


#Loop through array deleting each file/directory with the recursive force options

    for i in "${FILES[@]}"

      do

        rm -rf "$i"

      done

    exit

2 个答案:

答案 0 :(得分:2)

问题不在于数组或空格,而在于文件路径中的~~实际上并不是路径的有效部分,但是shell将替换为您的主目录路径替换它...除非它在引号中:

$ echo ~/Library/Preferences/Adobe InDesign
/Users/gordon/Library/Preferences/Adobe InDesign
$ echo "~/Library/Preferences/Adobe InDesign"
~/Library/Preferences/Adobe InDesign

所以你可以将~放在引号之外:

FILES=(
~/"Library/Preferences/Adobe InDesign"
~/"Library/Caches/Adobe InDesign"
~/"Library/Saved Application State/com.adobe.InDesign.savedstate"
)

或者使用$ HOME(在双引号中替换):

FILES=(
"$HOME/Library/Preferences/Adobe InDesign"
"$HOME/Library/Caches/Adobe InDesign"
"$HOME/Library/Saved Application State/com.adobe.InDesign.savedstate"
)

答案 1 :(得分:0)

我有时会使用这个技巧:

with_expanded_paths()
{
  typeset IFS
  IFS=""
  "$@"
}
with_expanded_paths rm -rf "~/file with spaces"

我是从记忆中写下来的,所以可能需要稍作调整。