0

I wrote a script to calculate the sum of the df total capacity in Linux' Bash shell. Is there a way to calculate it without creating a file?

#!/bin/bash

if [ -f /tmp/df_test.txt ]
then
    rm  tmp/df_test.txt
    echo "Remove files."
    else
    touch /tmp/df_test.txt
    echo "file creation."
        arr=(`df | awk -F " " '{print $2}' | sort -n | sed -e "1d"`)
        for i in ${arr[*]}
        do
            echo $i >>/tmp/df_test.txt 2>/dev/null
        done
fi
echo "ex) 1GB = 1000MB = 1000000KB"
echo "————————————————————————————————————"
cat /tmp/df_test.txt | awk '{sum+=$1; print$0} END {print"df total=KB)",sum} ' | sort -r | sed '2,$d'
echo "————————————————————————————————————"
rm /tmp/df_test.txt

I'd also like to make my code more concise but I'm out of ideas.

Machavity
  • 30,841
  • 27
  • 92
  • 100
김태웅
  • 15
  • 2

1 Answers1

0

You can try this to get total usage in human readable units

df --total --human | awk 'END {print $2}' 
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134