简体   繁体   中英

Counting All FIles/Directories in a Specified Directory - bash/shell scripting

The finished product is meant to recursively count everything in a specified directory, or the current if no arguments are entered. Right now Im just trying to get it to count anything in the specified directories. I'm having difficulty getting the last statements to count anything at all. It will echo 0 files in the directory.

Could anyone give me any tips? I'm still a beginner so take it easy on me, thanks!

#!/bin/bash
#A shell script program that counts recursively how many directories/files exist in a given directory.

declare -i COUNT=0
declare -i COUNT2=0
#The script will treat COUNT as an integer that is 0 until modified.
if [ "$#" -eq "0" ]
    then

        for i in *
        do
            ((COUNT++))
        done
    ((COUNT--)) #This is done because there is always an overcount of 1.
    echo "There are $COUNT files and/or directories in the current directory here."
fi

if [[ -d $1 ]]
    then
        for i in $1
        do
            ((COUNT++))
        done
    ((COUNT--)) #This is done because there is always an overcount of 1.
    echo "There are $COUNT files and/or directories in $1."
fi

if [[ -d $2 ]]
    then
        for i in $2
        do
            ((COUNT2++))
        done
    ((COUNT2--)) #This is done because there is always an overcount of 1.
    echo "There are $COUNT2 files and/or directories in $2."
fi
exit 0

First of, you can do what you want with a one-liner:

find . | wc -l  

find . means "search in the current directory and all subdirectories". Since there is no other argument, it will simple list everything. Then, I use a pipe and wc , which stands for "word count". The -l option means "output only the number of lines".

Now, for your code, here are some tips. First, I don't really understand why you repeat your code three times (for 0, $1 and $2). You could simply do:

dir="$1"
if [ -z "$dir" ]; then dir="."; fi

You store the value of the command-line argument in $dir and if none is provided, (-z means "is empty"), you assign a default value to dir.

for i in $1 won't work if $1 is the path to a directory. So instead, you can use

for i in $(ls $dir)

Also, in your code, you don't count recursively. Is it voluntary or you don't know how to proceed ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM