Shell script: Check that file is file and not directory
I'm currently working on a small cute shell script to loop through a specific folder and only output the files inside it, excluding any eventual directories. Unfortunately I can't use find
as I need to access the filename variables.
Here's my current snippet, which doesn't work:
for fi开发者_运维知识库lename in "/var/myfolder/*"
do
if [ -f "$filename" ]; then
echo $filename # Is file!
fi
done;
What am I doing wrong?
You must not escape /var/myfolder/*, meaning, you must remove the double-quotes in order for the expression to be correctly expanded by the shell into the desired list of file names.
What you're doing wrong is not using find
. The filename can be retrieved by using {}
.
find /var/myfolder -maxdepth 1 -type f -exec echo {} \;
Try without double quotes around /var/myfolder/* (reason being is that by putting double quotes you are making all the files a single string instead of each filename a separate string
for filename in "/var/myfolder/*"
The quotes mean you get one giant string from that glob -- stick an echo _ $filename _
immediately before the if
to discover that it only goes through the 'loop' once, with something that isn't useful.
Remove the quotes and try again :)
You can use find and avoid all these hassles.
for i in $(find /var/myfolder -type f)
do
echo $(basename $i)
done
Isn't this what you're trying to do with your situation? If you want to restrict depth, use the -maxdepth
option to find.
精彩评论