Bash脚本删除除特定文件和目录之外的所有文件和目录 [英] Bash script to remove all files and directories except specific ones
问题描述
我正在尝试编写一个非常简单的Bash shell脚本,该脚本将在特定目录中进行cd安装,它将删除所有文件和目录(除了一些选定的文件和目录之外),然后将其cd返回到原始目录.
我的代码是:
#!/bin/bash
cd /path/to/desired/directory
shopt -s extglob
rm !\(filename1\|filename2\|filename3\) -rf
cd -
我尝试了多种写法,用单引号或双引号或反斜杠来写符号'('和'|',但没有任何效果.请注意,shopt -s extglob
和rm !(filename1|filename2) -rf
在脚本之外也可以正常工作.>
可能我犯了一个我看不见的标准和基本的bash脚本错误,但是经验将要来临...
有什么建议!? 预先感谢.
我马上就能看到两个问题:
-
rm
的-rf
参数必须在文件名之前 - extglob指示符
!
,(
,|
和)
不应 用反斜杠转义
尝试以下方法:
rm -rf !(filename1|filename2|filename3)
如果仍然不起作用,请删除-f
参数,您将收到有关发生问题的错误消息,而不是默默地抑制它们.要打印出每个已删除文件的名称,您还可以添加-v
选项.
I am trying to write a very simple Bash shell script that will cd in a specific directory, it will remove all files and directories except some few selected ones and then cd back to the original dir.
My code is:
#!/bin/bash
cd /path/to/desired/directory
shopt -s extglob
rm !\(filename1\|filename2\|filename3\) -rf
cd -
I have tried many different ways to write the symbols '(' and '|', with single or double quotes or backslash but nothing worked. Note, that shopt -s extglob
and rm !(filename1|filename2) -rf
work fine outside a script.
Probably I am committing a standard and fundamental bash-scripting error that I cannot see, but experience is to come...
Any suggestions!? Thanks in advance.
Two problems I can see right off the bat:
- The
-rf
argument torm
must come before the filenames - The extglob specifiers
!
,(
,|
and)
should not be escaped with backslashes
Try this instead:
rm -rf !(filename1|filename2|filename3)
If it's still not working, remove the -f
argument, and you'll get error messages about what's going wrong instead of silently suppressing them. To print out the name of each file removed, you can add the -v
option as well.
这篇关于Bash脚本删除除特定文件和目录之外的所有文件和目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!