Reputation: 11
I want to loop through all files in given path to directory and echo the type of each file.
So far I managed to do these:
for file in `ls $path`
do
if [[ -f "$file" ]];
then
echo "file"
fi
if [[ -d "$file" ]];
then
echo "DIR"
fi
done
but I don't get anything evendough I have two directories inside a path?
Upvotes: 0
Views: 97
Reputation: 4484
Perhaps you want this:
find your/path -maxdepth 1 -type f -exec file {} \;
If you need to recursively dig into sub-folders, just remove -maxdepth 1
option like this:
find your/path -type f -exec file {} \;
If you need to also print the folder name, and its type (type == "Directory", of course), just remove the -type f
option like this:
find your/path -exec file {} \;
Upvotes: 0
Reputation: 185053
Avoid parsing ls
output, a better solution is (using glob
) :
path=/tmp/foobar
cd "$path"
for file in *
do
if [[ -f "$file" ]]
then
echo "FILE $file"
fi
if [[ -d "$file" ]]
then
echo "DIR $file"
fi
done
Upvotes: 1
Reputation: 87251
ls
doesn't display $path
itself. You can add it back manually:
for file in `ls -- "$path"/`
do
file="$path/file" # New code line.
if [[ -f "$file" ]]
then
echo "file"
fi
if [[ -d "$file" ]]
then
echo "DIR"
fi
done
However, please consider Etan Reisner's comment, and get rid of ls
, because it's most probably unnecessary in your use case.
Upvotes: 0