如何*仅*获得bash中磁盘上可用的字节数? [英] How can I *only* get the number of bytes available on a disk in bash?

查看:74
本文介绍了如何*仅*获得bash中磁盘上可用的字节数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

df在概述方面做得很好.但是,如果我想在shell脚本中将变量设置为磁盘上可用的字节数呢?

df does a great job for an overview. But what if I want to set a variable in a shell script to the number of bytes available on a disk?

示例:

$ df
Filesystem            1K-blocks     Used Available Use% Mounted on
/dev/sda             1111111111  2222222  33333333  10% /
tmpfs                  44444444      555  66666666   1% /dev/shm

但是我只想返回33333333(/上可用的字节),而不是整个df输出.

But I just want to return 33333333 (bytes available on /), not the whole df output.

推荐答案

可移植:

df -P /dev/sda1 | awk 'NR==2 {print $4}'

-P选项可确保df将以期望的格式打印输出,并且即使设备名很长,也不会特别打断行名.将设备名称作为参数传递给df消除了解析的任何危险,例如在查询/dev/sda1时获取/dev/sda10的信息. df -P仅打印两行,标题行(您将忽略)和一条数据行,您将在其中打印所需的列.

The -P option ensures that df will print output in the expected format, and will in particular not break the line after the device name even if it's long. Passing the device name as an argument to df removes any danger from parsing, such as getting information for /dev/sda10 when you're querying /dev/sda1. df -P just prints two lines, the header line (which you ignore) and the one data line where you print the desired column.

df可能会显示包含空格的设备名称,例如,如果卷是通过名称挂载的,并且名称包含空格,或者是其远程挂载点包含空格的NFS卷.在这种情况下,没有完全可移植的方法来解析df的输出.如果您确信df将显示传递给它的确切设备名称(并非总是如此),则可以将其剥离:

There is a risk that df will display a device name containing spaces, for example if the volume is mounted by name and the name contain spaces, or for an NFS volume whose remote mount point contains spaces. In this case, there's no fully portable way to parse the output of df. If you're confident that df will display the exact device name you pass to it (this isn't always the case), you can strip it:

df -P -- "$device" | awk -vn=${#device} 'NR==2 {$0 = substr($0, n+1); print $3}'

这篇关于如何*仅*获得bash中磁盘上可用的字节数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆