Friday, May 13, 2011

Cool Bash One Liner; extracting a value from command output

Here's a cool 1-liner to find the partition that has the least amount of free space. The command will simply return the number representing the percentage used on that partition (with the most amount of space used).

Here it is:

df -h | grep -Eo [0-9]+% | sort -n | tail -1 | cut -d "%" -f1


To break if down:

  1. the "df -h" command shows you disk free info of all your partitions in human readable form
  2. the "grep -Eo [0-9]+%" command takes the output of the previous command and returns a list with only the percentages. It does this based on the -E option which stands for Extended Regex and the -o option which outputs only those characters that match the Regex.
  3. the "sort -n" command then takes the output from the previous command and sorts it ascending
  4. the "tail -1" command then takes the output from the previous command and shows only the last 1 line
  5. the "cut -d "%" -f1 cuts of the percentage sign, leaving you only with the number
The output of this could be used in another script that perhaps runs as a cron job every few times a day and based on the result, sends you an email. You can use your imagination I'm sure to see how this could be useful.

Happy Bashing!

No comments: