0

如何最好地处理数组中混合的文件和目录。我需要创建一个文件和文件夹数组,并循环遍历数组,并将数组中的每个项目置于带有 -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
4

2 回答 2

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"
)
于 2012-09-27T22:35:54.417 回答
0

我有时会使用这个技巧:

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

我是凭记忆写的,所以可能需要稍作调整。

于 2012-09-27T20:11:59.763 回答