shell脚本实现输出给定目录下一层各文件(夹)大小

使用方法:
$sh xxx.sh 指定路径

脚本结果图
#!/bin/bash

function  caculateSubFileSize(){

  filetotal=$2

  if [ -f $1 ]; then
    #文件
    size=$(ls -l $subfilePwd | awk '{print $5}')
    filetotal=$((size+filetotal))
  elif [[ -d $1 ]]; then

    for subfile in `ls $1`; do
     subfilePwd="$1/$subfile"
     if [ -d $subfilePwd ]; then
       #文件夹
       caculateSubFileSize $subfilePwd $filetotal
     elif [[ -f $subfilePwd ]]; then
       #文件
       size=$(ls -l $subfilePwd | awk '{print $5}')
       filetotal=$((size+filetotal))
     else
       echo "这是什么东西?----- $subfilePwd"
     fi
    done

  else
    echo "这是什么东西?----- $subfilePwd"
  fi

  return $filetotal
}

function caculateFilesSize(){

  cd $1
    
  fileSizeArr=()

  for file in `ls $1`; do

    subTotal=0
    subfilePwd="$1/$file"

    caculateSubFileSize $subfilePwd 0
    subTotal=$?


    tmp=1000
    tmp2=$((tmp*tmp))
    fileSize=''

    if [ $filetotal -gt $tmp ]; then
      if [ $filetotal -gt $tmp2 ]; then
        fileSize="$(awk 'BEGIN{printf "%.2f\n",'$filetotal'/'$tmp2'}')M"
      else
        fileSize="$(awk 'BEGIN{printf "%.2f\n",'$filetotal'/'$tmp'}')K"
      fi
    else
      fileSize="$(awk 'BEGIN{printf "%.2f\n",'$filetotal'/'1'}')B"
    fi

    fileSizeArr+=($fileSize)

    echo $file  $fileSize
  done

  echo '--------纯大小输出,方便填入wiki文档--------'
  for i in ${fileSizeArr[@]}; do
      echo $i
  done
}

caculateFilesSize $1




你可能感兴趣的:(shell脚本实现输出给定目录下一层各文件(夹)大小)