Shell-Script

使用 rm 刪除多個文件,只對所有內容進行一次確認(rm -i)?

  • May 21, 2021

我有一個別名rm='rm -irv',我想刪除一堆文件和/或目錄,但我只想要一條確認消息,例如rm: descend into directory 'myfolder'?

我不介意確認每個目錄但不確認每個目錄中的每個文件。zsh 功能rm *orrm something/*執行良好,但有時我只是刪除文件rm *.txt或單個文件rm document.txt,但我仍然希望至少 1 次確認。

該解決方案 與我正在尋找的非常接近,但並非在每種情況下都適用。因此,假設目錄“myfolder”包含 100 個文件,那麼我想要如下所示的內容:

~ > ls -F
myfolder/    empty.txt    file.txt    main.c

~ > rm *
zsh: sure you want to delete all 4 files in /home/user [yn]? n

~ > rm myfolder
rm: descend into directory 'myfolder'? y
removed 'file1.txt'
removed 'file2.txt'
...
removed 'file100.txt'
removed directory 'myfolder'

~ > rm main.c
rm: remove regular file 'main.c'? y
removed 'main.c'

~> rm *.txt
rm: remove all '*.txt' files? y
removed 'empty.txt'
removed 'file.txt'

獲得您的問題中列出的確切提示和輸出實際上是不可能的(或大量的工作),但以下內容應該讓您涵蓋所有實際目的:

# Disable the default prompt that says
# 'zsh: sure you want to delete all 4 files in /home/user [yn]?'
setopt rmstarsilent

# For portability, use the `zf_rm` builtin instead of any external `rm` command.
zmodload -Fa zsh/files b:zf_rm

rm() {
 # For portability, reset all options (in this function only).
 emulate -L zsh

 # Divide the files into dirs and other files.
 # $^ treats the array as a brace expansion.
 # (N) eliminates non-existing matches.
 # (-/) matches dirs, incl. symlinks pointing to dirs.
 # (-^/) matches everything else.
 # (T) appends file type markers to the file names.
 local -a dirs=( $^@(TN-/) ) files=( $^@(TN-^/) )

 # Tell the user how many dirs and files would be deleted.
 print "Sure you want to delete these $#dirs dirs and $#files files in $PWD?"

 # List the files in columns à la `ls`, dirs first.
 print -c - $dirs $files

 # Prompt the user to confirm.
 # If `y`, delete the files.
 #   -f skips any confirmation.
 #   -r recurses into directories.
 #   -s makes sure we don't accidentally the whole thing.
 # If this succeeds, print a confirmation.
 read -q "?[yn] " &&
     zf_rm -frs - $@ && 
     print -l '' "$#dirs dirs and $#files files deleted from $PWD."
}

有關更多資訊zf_rm,請參閱http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002files-Module

(TN-^/)可以在此處找到有關 glob 限定符的更多資訊:http: //zsh.sourceforge.net/Doc/Release/Expansion.html#Glob-Qualifiers

引用自:https://unix.stackexchange.com/questions/624651