遞歸計算檔案和目錄

遞歸計算檔案和目錄

我需要一些幫助:

假設我在一個目錄中,在這個目錄中還有其他目錄和檔案等......

我想使用遞歸函數來計算其中和子目錄中的所有檔案和目錄。

我知道我可以透過使用 wc ... grep 或 find 來解決問題,但我真的想在這裡使用我的第一個遞歸函數。

這是我到目前為止所做的,但它不能正常工作

    counting(){


    for i in $(ls -a $1)
    do
          if [ -d $1/$i ];then
          let d++
          cd $1/$i       
          counting $i
          cd ..
          elif [ -f $1/$i ];then
          let f++
          fi
    done

  }

counting $1
echo "number of files = $f ; number of directories = $d"

答案1

以下是您可以改進的一些事項(不保證完整性):

  1. 絕不解析 的輸出ls
    一旦任何檔案或目錄名稱包含空格(這在大多數現代檔案系統上是完全合法的),您的腳本就會中斷。
    相反,請使用 shell 的通配符功能:

    shopt -s dotglob # to make the * glob match hidden files (like ls -a)
    for i in "$1"/*
    
  2. 始終引用變數。
    您的 shell 會查看空白字元(空格、換行符等)來決定一個指令參數的結束位置和另一個指令參數的起始位置。考慮以下範例:

    filename="foo bar"
    
    touch $filename
    # gets expanded to `touch foo bar`, so it creates two files named "foo" and "bar"
    
    touch "$filename"
    # gets expanded to `touch "foo bar`", so it creates a single file named "foo bar"
    
  3. 太多cd

    cd $1/$i       
    counting $i
    
    # which in turn calls ...
    ls -a $1
    

    ls./foo/bar/bar- 除了解析和不帶引號的變數之外,當您擁有的全部內容都是 時,這將嘗試列出目錄的內容./foo/bar

相關內容