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


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...