程式扎記: [Linux 常見問題] Shell - Calculate the free disk space in GB

標籤

2016年2月19日 星期五

[Linux 常見問題] Shell - Calculate the free disk space in GB

Question
In some case, you may need to know the size of free disk space. Then you can leverage the function below which leverage command df.

Sample Code
Below sample code will return the size in GB of free disk space.
  1. freespace()  
  2. {  
  3.     df --block-size=1G -P $1 | grep -vE '^Filesystem|tmpfs|cdrom|Available' | awk '{ print $4 }'  
  4. }  
This function freespace take one argument and show the free disk space of the given path.

Usage Example 
The command df can show the below output to indicate the free disk space format:
# df -h /
檔案系統 容量 已用 可用 已用% 掛載點
/dev/mapper/centos-root 50G 9.0G 41G 19% /

If you want to show the disk space in GB with the 'G', leveraging the argument -B, --block-size=SIZE (scale sizes by SIZE before printing them)
# df --block-size=1G /
檔案系統 1G-區段 已用 可用 已用% 掛載點
/dev/mapper/centos-root 50 9 41 19% /

Then you want to filter out the line containing the size of free disk space and get rid of the title, try this:
# echo $LANG
zh_TW.UTF-8
# export LANG=en_US.UTF-8 // Change language setting 
# df --block-size=1G /
Filesystem 1G-blocks Used Available Use% Mounted on
/dev/mapper/centos-root 50 9 41 19% /

# df --block-size=1G / | grep -vE '檔案系統|Filesystem'
/dev/mapper/centos-root 50 9 41 19% /

Finally, we just use command awk to retrieve the target field:
# df --block-size=1G / | grep -vE '檔案系統|Filesystem' | awk '{ print $4 }'
41


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!