You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash新手求助:编写脚本统计当前目录文件总大小(排除子目录)

Bash Script to Sum Regular File Sizes (No Advanced Commands)

Hey there! Since you're new to Bash and can't use tools like grep or du, let's build a simple script using basic shell features and the output from ls -l. Here's a solution that works exactly how you need it:

#!/bin/bash

# Initialize total size counter to 0
total_size=0

# Loop through each line of ls -l output (skipping the first "total" line)
ls -l | while read -r perm links owner group size month day time filename; do
    # Check if the item is a regular file (starts with "-" in permissions)
    if [[ "$perm" == "-"* ]]; then
        # Add the file's size to the total
        total_size=$((total_size + size))
    fi
done

# Print the final total
echo "Total size of all regular files in current directory: $total_size bytes"

Let's break down how this works:

  • Initializing the counter: We start with total_size=0 to keep track of our running total.
  • Reading ls -l output: The while read loop splits each line of ls -l into easy-to-use variables. Instead of relying on column numbers like $5 or $9 (which breaks if filenames have spaces), we map each column to a variable—size grabs the file size column, and filename takes the rest (so spaces in filenames don't break things).
  • Filtering out directories: The if check looks at the first character of the permission string (perm). If it starts with -, it's a regular file—we skip directories (which start with d) and other item types like symlinks.
  • Adding up sizes: Bash's built-in arithmetic expansion $((...)) lets us add the current file's size to our total without needing any external commands.

Quick tips:

  • This script handles filenames with spaces correctly, which is a big win over trying to use $9 directly.
  • If you want the total in a friendlier format (like KB/MB), you could add a simple calculation at the end (e.g., echo "Total: $((total_size / 1024)) KB"), but that's optional!

内容的提问来源于stack exchange,提问作者Arnau Martínez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:02:11