Article 6DZ2Z Adding Size to Folder Names on Linux Server

Adding Size to Folder Names on Linux Server

by
DaveyMames
from LinuxQuestions.org on (#6DZ2Z)
Hi, I've got this folder on my server:
zTransfersToServeDrive1

Inside that is another folder called "Transfers Today"
Inside that are folders of TV series. I would like each TV Series folder to have it's file size added onto the end of it's folder. No subfolders of the TV series folders should have that done. However my script is adding the filesize to all subfolders. Can you please correct my script to do what I want.

Code:#!/bin/bash

source_dir=/home/daveymames/torrents/rtorrent/"zTransfersToServeDrive1"
destination_dir=ServDrive1:/""

calculate_total_size() {
dir_path="$1"
total_size=$(du -cb "$dir_path" | tail -n1 | awk '{size=$1; if (size >= 1024*1024*1024) {size=size/1024/1024/1024; unit="GB"} else if (size >= 1024*1024) {size=size/1024/1024; unit="MB"} else {size=size/1024; unit="KB"}; printf "%.2f %s", size, unit}')
echo "$total_size"
}

append_size_to_name() {
dir_path="$1"
total_size="$2"
new_name="${dir_path} [${total_size}]"
mv "$dir_path" "$new_name"
}

for sub_dir in "$source_dir"/*/*; do
if [[ -d "$sub_dir" ]]; then
size=$(calculate_total_size "$sub_dir")
append_size_to_name "$sub_dir" "$size"
fi
done
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments