簡體   English   中英

計算指定目錄中的所有文件/目錄-bash / shell腳本

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

成品用於遞歸計數指定目錄中的所有內容,如果沒有輸入任何參數,則為當前目錄。 現在,我只是想讓它計算指定目錄中的任何內容。 我很難獲得最后的聲明來計算任何東西。 它將在目錄中回顯0個文件。

誰能給我提示嗎? 我仍然是初學者,所以請放心,謝謝!

#!/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

首先,您可以使用單線工作:

find . | wc -l  

find . 表示“在當前目錄和所有子目錄中搜索”。 由於沒有其他參數,它將簡單列出所有內容。 然后,我使用管道和wc ,它代表“字數統計”。 -l選項的意思是“僅輸出行數”。

現在,對於您的代碼,這里有一些提示。 首先,我不太了解為什么要重復三次代碼(分別為0,$ 1和$ 2)。 您可以簡單地執行以下操作:

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

您將命令行參數的值存儲在$ dir中,如果未提供任何參數(-z表示“為空”),則將默認值分配給dir。

for i in $1如果$1是目錄路徑,則$1中的for i in $1將不起作用。 因此,您可以使用

for i in $(ls $dir)

另外,在您的代碼中,您無需遞歸計數。 是自願的還是您不知道如何進行?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM