Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux rm 刪除以破折號開頭的檔案/目錄:雙破折號與相對路徑兩法

編輯:Linux 教學

檔名以 - (破折號) 開頭時,rm 會誤將其視為選項參數而報錯 invalid option。標準解法有兩種:-- 終止選項解析、./ 相對路徑前綴。

問題重現

$ rm -slow_query_130103.txt.gz
rm: invalid option -- s
Try 'rm ./-slow_query_130103.txt.gz' to remove the file.
Try 'rm --help' for more information.

方法一:雙破折號 -- (POSIX 標準)

rm -- -slow_query_130103.txt.gz

-- 告訴 rm 後續參數不再解析選項,全部視為檔案路徑。

方法二:相對路徑前綴 ./

rm ./-slow_query_130103.txt.gz

路徑以 ./ 開頭,不被視為選項。

通用原則

  • 所有 GNU Coreutils 指令 (cp, mv, ls, cat...) 均支援 -- 分隔選項與檔案。
  • 腳本處理不可控檔名時,**務必** 使用 rm -- "$file" 或 rm "./$file" 防注入。
  • 檔名包含空白、換行、通配符時,同樣需加引號:rm -- "-file name.txt"。

批次刪除以破折號開頭的檔案

# 當前目錄
for f in -*; do rm -- "$f"; done

# 遞歸 (需 find)
find . -name '-*' -exec rm -- {} +

其他特殊檔名處理

檔名特徵處理範例
以 # 開頭rm ./\#file
包含空白rm "file name.txt"
包含換行rm $'file\nname.txt'
唯一 inode 刪除find . -inum 12345 -exec rm -- {} +
Copyright © Windows教程網 All Rights Reserved