bash - 删除目录列表(包括其内容)
下面的脚本给出了这个错误:
rm: illegal option -- 4
rm: illegal option -- 5
rm: illegal option -- 4
rm: illegal option -- 3
rm: illegal option -- 2
脚本:
#!/bin/bash
keep_no=$1+1
cd "/mydirec/"
rm -rf `ls | sort -nr | tail +$keep_no`
我希望脚本接受一个参数(要保留的目录数),然后删除所有目录(包括它们包含的文件),除了(在脚本中传递的数字 - 按数字直接名称按降序排列)。
即如果 /mydirec/ 包含这些目录名称:
53
92
8
152
77
并且脚本的调用方式如下: bash del.sh 2
那么 /mydirec/ 应该包含这些目录(因为它删除了那些不是按降序排列的前 2 个目录的目录):
152
92
有人可以吗帮助语法?
The below script gives this error:
rm: illegal option -- 4
rm: illegal option -- 5
rm: illegal option -- 4
rm: illegal option -- 3
rm: illegal option -- 2
the script:
#!/bin/bash
keep_no=$1+1
cd "/mydirec/"
rm -rf `ls | sort -nr | tail +$keep_no`
I would like the script to accept an argument (of num of direcs to keep) then remove all directories (including their containing files) except for the (number passed in the script - ordering by the numerical direc names in descending order).
ie if /mydirec/ contains these direc names:
53
92
8
152
77
and the script is called like: bash del.sh 2
then /mydirec/ should contains these direcs (as it removes those that aren't the top 2 in desc order):
152
92
Can someone please help with the syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
手动验证脚本的输出,然后通过 sh 执行脚本:
Verify the output of the script manually, then execute the script through sh:
应该阅读:
但最好不要解析 ls 输出。使用查找代替。
Should read:
But it is good practice not to parse ls output. Use find instead.
如果要保留两个目录(不是删除),则需要计算目录总数。
xargs
实用程序是将参数列表传递给rm
的更方便的方法。If you want to leave two directories (not to delete) you need to calculate total number of directories. And
xargs
utility is more convenient way to pass a list of arguments torm
.