Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

shell - How to do something to every file in a directory using bash?

I started with this:

command *

But it doesn't work when the directory is empty; the * wildcard becomes a literal "*" character. So I switched to this:

for i in *; do
   ...
done

which works, but again, not if the directory is empty. I resorted to using ls:

for i in `ls -A`

but of course, then file names with spaces in them get split. I tried tacking on the -Q switch:

for i in `ls -AQ`

which causes the names to still be split, only with a quote character at the beginning and ending of the name. Am I missing something obvious here, or is this harder than it ought it be?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you only want to do something to files, the simple solution is to test if $i is a file:

for i in * 
do
    if test -f "$i" 
    then
       echo "Doing somthing to $i"
    fi
done

You should really always make such tests, because you almost certainly don't want to treat files and directories in the same way. Note the quotes around the "$i" which prevent problems with filenames containing spaces.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...