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=0to keep track of our running total. - Reading
ls -loutput: Thewhile readloop splits each line ofls -linto easy-to-use variables. Instead of relying on column numbers like$5or$9(which breaks if filenames have spaces), we map each column to a variable—sizegrabs the file size column, andfilenametakes the rest (so spaces in filenames don't break things). - Filtering out directories: The
ifcheck looks at the first character of the permission string (perm). If it starts with-, it's a regular file—we skip directories (which start withd) 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
$9directly. - 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
相关产品推荐
相关产品推荐

