很多天前,我发现了这个有用的 bash 别名(我的~/.bash_aliases 的内容)
# aliases
# finds temporary files ending with '~' and deletes them
alias rm~='find . -name '*~' -print0 | xargs -0 /bin/rm -f'
Run Code Online (Sandbox Code Playgroud)
现在我尝试使用rm~
aftercd
到包含 3 个以~
我在终端中收到此错误,文件没有被删除
find: paths must precede expression: 1n.in~
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Run Code Online (Sandbox Code Playgroud)
此外,当我尝试rm~
from 时/home/me
,它似乎什么也没做。或者它可能需要很多时间。
请告诉我为什么我会出错,以及如何解决它。
谢谢!
gni*_*urf 26
你的 bash 别名写得不好(单引号用得不好)。相反,它应该是:
alias rm~='find . -name "*~" -print0 | xargs -0 /bin/rm -f'
Run Code Online (Sandbox Code Playgroud)
现在,我个人不喜欢管道和的无用用途xargs
,所以你的别名最好写成:
alias rm~='find . -name "*~" -type f -exec /bin/rm -fv -- {} +'
Run Code Online (Sandbox Code Playgroud)
该-type f
选项以便只找到文件(不是目录,链接等),该-v
选项rm
,以便详细(打印出它的删除)。将+
在年底使find
运行rm
的所有找到的文件(产卵只有一个实例rm
,而不是每个文件一个)。
现在从man bash
:
对于几乎所有目的,别名都被 shell 函数取代。
与其使用别名,不如使用函数:在.bash_aliases
文件中注释您的别名(即,#
在该行前面放置 a ),然后在文件.bashrc
中放置此函数(文件中的任何位置,最后都可以) :
rm~() {
find . -name "*~" -type f -exec /bin/rm -fv -- {} +
}
Run Code Online (Sandbox Code Playgroud)
此外,正如其他答案所提到的,您可以使用该-delete
命令进行查找。在这种情况下,您的rm~
功能将是:
rm~() {
find . -name "*~" -type f -printf "Removing file %p\n" -delete
}
Run Code Online (Sandbox Code Playgroud)
事实上,你可以创建一个很酷的函数,它接受一个参数,比如--dry-run
,它只会输出它将删除的内容:
rm~() {
case "$1" in
"--dry-run")
find . -name "*~" -type f -printf "[dry-run] Removing file %p\n"
;;
"")
find . -name "*~" -type f -printf "Removing file %p\n" -delete
;;
*)
echo "Unsupported option \`$1'. Did you mean --dry-run?"
;;
esac
}
Run Code Online (Sandbox Code Playgroud)
然后用作:
rm~ --dry-run
Run Code Online (Sandbox Code Playgroud)
只显示将被删除的文件(但不删除它们),然后
rm~
Run Code Online (Sandbox Code Playgroud)
当你对此感到满意时。
适应和扩展您的需求!
笔记。您必须打开一个新终端才能使更改生效。
*~
在分配给您的别名之前,它会被 shell 扩展。实际任务是:
alias rm~='find .name some~ file~ 1n.in~ -print0 | xargs -0 /bin/rm -f'
Run Code Online (Sandbox Code Playgroud)
我建议使用函数而不是别名,它们在引号方面更强大且更容易处理。
当我们在做的时候,删除多余的.
(如果没有给出参数,则隐含当前目录)并停止滥用,xargs
因为一个-delete
选项已经存在。
rm~() { find -name '*~' -ls -delete; }
Run Code Online (Sandbox Code Playgroud)
该-ls
选项是可选的,但添加它会显示哪些文件已被删除。