bash 命令 - 在 `ls` 中使用 for i 和 if 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14224192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:12:18  来源:igfitidea点击:

bash command - using for i in `ls` with an if statement

linuxbash

提问by sputn1ck

I'm trying to clean up some directories that are all named in sequence 1001, 1002, 1003 and I can't seem to get this script to work to delete directories with a value less than a number

我正在尝试清理一些以 1001、1002、1003 顺序命名的目录,但我似乎无法使用此脚本来删除值小于数字的目录

Contents of the DIR

目录的内容

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

My command

我的命令

for i in `ls`; do if (( $i < 1011 )) then echo rm $i -rf; done

but I get the error

但我得到了错误

-su: syntax error near unexpected token `then'

Can anyone point me in the right direction?

任何人都可以指出我正确的方向吗?

回答by Andreas Florath

for i in *; do [ $i -lt 1011 ] && rm -fr $i; done

does the job.

做这项工作。

Note: this really removes the files and does not just print the remove commands.

注意:这确实会删除文件,而不仅仅是打印删除命令。

回答by Spencer Rathbun

Looping over ls is bad, as explained here. Instead, use find, like so:

循环 ls 是不好的,正如这里所解释的。相反,使用查找,如下所示:

find . -regex '\./10[01][0-9]' -exec echo rm '{}' -rf \;

回答by Bela Vizer

try

尝试

for i in `ls`; do if [ $i -lt 1011 ]; then echo rm $i -rf; fi; done

edited

已编辑

回答by gustaf r

do

that's the reason.

这就是原因。

for i in `ls` ; do whatever ; done