刪除在 Mac OS X 上不使用通配符的 rm 指令

刪除在 Mac OS X 上不使用通配符的 rm 指令

我試圖透過 bash 腳本刪除所有使用者帳戶的以下文件,但通配符 * 似乎不起作用。我一直在 mac os x 終端上運行腳本來在本地測試該腳本。

要刪除的plist檔案:com.apple.eap.bindings.XXXXXXX.plist

#!/bin/bash

for dir in /Users/*;
do
    if [[ -e "${dir}/Library/Preferences/com.apple.eap.bindings.*" ]]; then
        rm "${dir}/Library/Preferences/com.apple.eap.bindings.*"
    fi
done

上面的程式碼不會刪除有問題的文件,但如果我指向不帶通配符的確切文件名,它確實可以工作。我也嘗試刪除引號,但仍然無法刪除該檔案。有人可以幫忙嗎?

答案1

if [[ -e "${dir}/Library/Preferences/com.apple.eap.bindings.*" ]]; then

在這一行中,您將星號放在雙引號內。這使得它成為一個文字字符,而不是神奇地擴展為文件名的東西。

連結:bash 中的雙引號與星號檔名擴展肖恩已經指出的帖子

您必須使用不含引號的星號。要么像腳本的第一部分一樣,要么作為參數find

答案2

您可以考慮將此作為替代方案

#!/bin/bash
/usr/bin/find /Users/*/Library/Preferences -name "com.apple.eap.bindings.*.plist" -exec /bin/rm -fv "{}" \;

這將有效地刪除有問題的檔案。如果您不需要輸出,請刪除“v”開關。

答案3

如果這對任何人都有幫助,那麼這對我有用:

#!/bin/bash

for dir in /Users/*;
do
    if [ -z "$(echo ${dir}/Library/Preferences/com.apple.eap.bindings.*|grep -q '*')" ]; then
        rm ${dir}/Library/Preferences/com.apple.eap.bindings.*
    fi
done

相關內容