Welcome to OStack Knowledge Sharing 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...