在 bash shell 中添加文件大小

Jam*_*man 2 bash shell loops file add

我编写了一个 shell 脚本,它将目录作为参数并打印文件名和大小,我想知道如何将文件大小相加并存储它们,以便我可以在循环后打印它们。我已经尝试了一些东西,但到目前为止还没有取得任何进展,有什么想法吗?

#!/bin/bash

echo "Directory <$1> contains the following files:"
let "x=0"
TEMPFILE=./count.tmp
echo 0 > $TEMPFILE
ls $1 |
while read file
do
        if [ -f $1/$file ]
        then
                echo "file: [$file]"
        stat -c%s $file > $TEMPFILE
        fi
cat $TEMPFILE
done
echo "number of files:"
cat ./count.tmp
Run Code Online (Sandbox Code Playgroud)

帮助将不胜感激。

Rei*_*ase 5

您的代码中存在许多问题:

假设你只是想在这方面练习和/或想做一些不同于已经做的事情,你应该将语法更改为类似

#!/bin/bash

dir="$1"
[[ $dir == *'/' ]] || dir="$dir/"
if [[ -d $dir ]]; then
  echo "Directory <$1> contains the following files:"
else
  echo "<$1> is not a valid directory, exiting"
  exit 1
fi

shopt -s dotglob
for file in "$dir"*; do
  if [[ -f $file ]]; then
    echo "file: [$file]"
    ((size+=$(stat -c%s "$file")))
  fi
done

echo "$size"
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 您不必在 bash 中预先分配变量,$size假定为 0
  • 您可以(())用于不需要小数位的数学。
  • 您可以使用 globs ( *) 获取特定目录中的所有文件(包括目录、符号链接等...)(以及**用于递归的globstar )
  • shopt -s dotglob是必需的,因此它.whatever在全局匹配中包含隐藏文件。