Tarracon
Tarracon

Reputation: 55

Program to check if each item is file or directory in path

I've got this starting code, but i don't know where to go from here. Right now I'm using the path ~/Desktop, but it doesnt read the Desktop directory. And echos out 0 for number of directories and files.

#!/bin/sh

path="$1"
num_file=0
num_dir=0
for item in $path; do
if [ -d ]
then
     num_dir+=1
elif [ -f ]
then
     num_file+=1
fi
done
echo "The number of directories is $num_dir"
echo "The number of files is $num_file"

Upvotes: 0

Views: 102

Answers (1)

user unknown
user unknown

Reputation: 36229

path="$1"

dirs=$(find "$path" -mindepth 1 -type d -printf "d"); 
fils=$(find "$path" -mindepth 1 -type f -printf "f"); 

echo "dirs: ${#dirs} files: ${#fils}"

Printing the size of the variables, which only collected the character 'd' or 'f'.

To avoid visiting subdirs, add -maxdepth 1 to the find commands.

In your code, I see multiple problems:

for item in $path; do
for item in "$path"/* ; do

You have to use * to get a list of items.

if [ -d ]
if [ -d "$item" ]

If -d what? Well, the item.

 num_dir+=1
 ((num_dir+=1))

Double round parens to do arithmetik. In Bash - at least. Maybe some of the things you did work on a 'sh-Shell', but I doubt it.

Upvotes: 1

Related Questions