Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...