在Bash中循环遍历目录 [英] Looping over directories in Bash
问题描述
我有一个关于bash的工作原理的基本问题,以及一个相关的实际问题.
I have a fundamental question about how bash works, and a related practical question.
基本问题:假设我在一个包含三个子目录的目录中:a,b和c.
Fundamental question: suppose I am in a directory that has three subdirectories: a, b, and c.
输入验证码
for dir in $(ls)
do
echo $dir
done
吐出来:
a b c
a b c
a b c
即dir
始终将所有文件/目录的列表存储在我的cwd
中.我的问题是:为什么这在世界上会很方便?我认为一次dir
一次存储每个元素会更加有用和直观,也就是说,我希望输出
i.e, dir
always stores a list of all of the files/directories in my cwd
. My question is: why in the world would this be convenient? In my opinion it is far more useful and intuitive to have dir
store each element at a time, i.e I would want to have output
a
b
c
此外,根据答案之一-使用for dir in $(ls)
是错误的,但是当我使用for dir in $(ls -l)
时,我会得到甚至更多的a b c
副本(超过了cwd中的目录/文件).为什么会这样?
Also, as per one of the answers - it is wrong to use for dir in $(ls)
, but when I use for dir in $(ls -l)
I get even more copies of a b c
(more than there are directories/files in the cwd). Why is that?
我的第二个问题很实际:我如何遍历cwd
中所有以大写字母W开头的目录(不是文件!)?我从
My second question is practical: how do I loop over all the directories (not files!) in my cwd
that start with capital W? I started with
for dir in `ls -l W*`
但这失败了,因为a)问题1的原因和b)因为它不排除文件.建议表示赞赏.
but this fails because a) the reason in question 1 and b) because it doesn't exclude files. Suggestions appreciated.
推荐答案
永远不要这样解析ls
的输出(为什么不应该't解析ls(1)的输出.
Never ever parse the output of ls
like this (Why you shouldn't parse the output of ls(1)).
此外,您的语法错误.您的意思不是()
,您的意思是$()
.
Also, your syntax is wrong. You don't mean ()
, you mean $()
.
话虽如此,您可以执行以W开头的目录循环(或根据情况使用find
命令):
That being said, to loop over directories starting with W you would do (or use the find
command instead, depending on your scenario):
for path in /my/path/W*; do
[ -d "${path}" ] || continue # if not a directory, skip
dirname="$(basename "${path}")"
do_stuff
done
对于您从邪恶的ls循环获得的输出,它看起来应该不是这样.这是预期的输出,并说明了为什么您不想在一开始就使用ls:
As for the output you get from the evil ls-loop, it should not look like that. This is the expected output and demonstrates why you do not want to use ls in the first place:
$ find
.
./c
./a
./foo bar
./b
$ type ls
ls is hashed (/bin/ls)
$ for x in $(ls); do echo "${x}"; done
a
b
c
foo
bar
这篇关于在Bash中循环遍历目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!