Saturday, May 4, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 636  / 3 Years ago, thu, august 19, 2021, 6:07:03

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.


More From » command-line

 Answers
7

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

[#213] Saturday, August 21, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wherejuic

Total Points: 53
Total Questions: 123
Total Answers: 117

Location: Zambia
Member since Mon, Jan 23, 2023
1 Year ago
wherejuic questions
;