3

Currently I'm trying to check file size from reading a directory

read directory

dirsize=$(du -sh $directory)

if [[ "$dirsize" -ge 2MB ]]; then
  echo 'High'

elif [[ "$dirsize" -le 2MB ]]; then
  echo 'Low'

fi

The problem is when I check file size, the output will be like

4.0K ./......./... 32M ./......./...

So, when I write my code it doesn't work and I don't know how to fix. For example,

if [[ "$dirsize" -ge 2MB ]]; then
   echo 'High'

From code above, my point is to echo 'High' if file is greater than 2MB. Could you give advice please.

3
  • 1
    Your trying to compare strings with -ge and -le. String compares can only be == (equal) or != (not equal).
    – petep
    Oct 2 at 2:58
  • Use "du -bs" to get total bytes. And compare sizes.
    – petep
    Oct 2 at 3:06
  • Does this help?
    – Error404
    Oct 2 at 3:13

2 Answers 2

2

du returns the size and the file/directory name. As you only need the size you just read the first part. And you need the bytes, not the iec size.

You can use numfmt to convert iec numbers to bytes (see man numfmt).

Numbers can be compared by bash with number compare operators (see man test).

# use only the first part of the output from "du" and use size in bytes
read -r size _ <<<"$( du -sb directory )"
# convert 2M to bytes
size2m="$( numfmt --from=iec 2M )"

# now compare the pure numbers
if [[ ${size} -ge ${size2m} ]]; then
    echo "High"
fi

if [[ ${size} -le ${size2m} ]]; then
    echo "Low"
fi
1
  • btw for the first line read -r size _ <<<"$( du -sb directory )" what does "_ <<<" means??
    – user1637069
    Oct 4 at 5:26
1

The problem is when I check file size, the output will be like

4.0K ./......./... 32M ./......./...

That output is the output you chose by providing the -h (--human-readable) option to du. You will have more success when you leave it out. Then, all sizes are printed in the same unit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy