0

I am taking input as memory ex. 10M or 50G or 50 K

and I want to check this much size available in file system. for that I'm using df -h command

df -Ph . | awk 'NR==2 {print $4}' 

I am getting 140M and my input may vary like 10k , 10M and 10G

EX:

my input is 20G and available memory in filesystem is 140M

So now how can I compare these two sizes (50G >140M ?) and echo output result.

2 Answers 2

3

You can also use -h with sort

Example

$cat <<EOF | sort -h 50G 140M 10M 50K EOF 

Result :

50K 10M 140M 50G 

Explanation:

-h, --human-numeric-sort, compare human readable numbers (e.g., 2K 1G)

Or inside a bash :

compare() { cat <<EOF | sort -h $1 $2 EOF } set $(compare 50G 140M) echo "$1 <= $2" 

Result:

140M <= 50G 

Another way to write compare :

compare() { echo -e "$1 \0 $2" | sort -zh } 
2
  • its good. but can u explain how it is working. Commented Jan 13, 2017 at 8:25
  • @saidesh. A pipe connects cat and sort. Cat produce data to sort. $( cmd ) executes a command. And set affect to $1 .. $n the result of $( cmd ). Commented Jan 13, 2017 at 17:40
0

convert your available and input values to Kb and compare it..

#!/bin/bash echo -n "Enter the value ( value should end with G/M/K): " read DISK_VALUE AVAILABLE_SPACE=$(df -h . | awk 'NR==2{print $4}') AVAILABLE_SPACE_IN_KB=$(echo "${AVAILABLE_SPACE}" | awk '/M$/{print ($0+0)*1024}/G$/{print ($0+0)*1024*1024}/K$/{print $0+0}') COMPARE_VALUE_IN_KB=$(echo "${DISK_VALUE}" | awk '/M$/{print ($0+0)*1024}/G$/{print ($0+0)*1024*1024}/K$/{print $0+0}') echo "AVAILABLE_SPACE_IN_KB : ${AVAILABLE_SPACE_IN_KB}" echo "COMPARE_VALUE_IN_KB : ${COMPARE_VALUE_IN_KB}" if [ "${AVAILABLE_SPACE_IN_KB}" -lt "${COMPARE_VALUE_IN_KB}" ] then echo "Available space (${AVAILABLE_SPACE}) is lesser than Given Value (${DISK_VALUE})" else echo "Available space (${AVAILABLE_SPACE}) is greater than Given Value (${DISK_VALUE})" fi $ bash a.sh Enter the value : 1000K AVAILABLE_SPACE_IN_KB : 100 COMPARE_VALUE_IN_KB : 1000 Available space (100K) is lesser than Given Value (1000K) $ bash a.sh Enter the value : 101M AVAILABLE_SPACE_IN_KB : 102400 COMPARE_VALUE_IN_KB : 103424 Available space (100M) is lesser than Given Value (101M) 
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.