使用 df 获取可用磁盘空间以仅以 kb 为单位显示可用空间? [英] Get free disk space with df to just display free space in kb?

查看:37
本文介绍了使用 df 获取可用磁盘空间以仅以 kb 为单位显示可用空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试输出文件系统 /example 上的可用磁盘空间量.

I'm trying to output the amount of free disk space on the filesystem /example.

如果我运行命令 df -k/example 我可以得到关于可用磁盘空间的良好信息,以 kb 为单位,但只能通过人工和实际查看它.

If I run the command df -k /example I can get good information about available disk space in kb but only by being human and actually looking at it.

我需要获取这些数据并在我的 shell 脚本中的其他地方使用它.我最初考虑使用 cut 但后来我的脚本无法移植到其他磁盘,因为可用磁盘空间会有所不同,并且 cut 不会产生准确的结果.

I need to take this data and use it somewhere else in my shell script. I initially thought about using cut but then my script wont be portable to other disks as free disk space will vary and cut will not produce accurate results.

如何仅以 kb 为单位获得示例的可用磁盘空间的输出?

How can I get output of just the free disk-space of example in kb?

推荐答案

要获得 df 的输出以显示 kb 中的数据,您只需要使用 -k 标志:

To get the output of df to display the data in kb you just need to use the -k flag:

df -k

此外,如果您为 df 指定一个文件系统,您将获得该特定文件系统的值,而不是所有值:

Also, if you specify a filesystem to df, you will get the values for that specific, instead of all of them:

df -k /example

<小时>

关于您的问题的正文:您想提取给定文件系统上的可用磁盘空间量.这将需要一些处理.


Regarding the body of your question: you want to extract the amount of free disk space on a given filesystem. This will require some processing.

给定一个正常的 df -k 输出:

Given a normal df -k output:

$ df -k /tmp
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda1        7223800 4270396   2586456  63% /

您可以使用 awkcut 获得 Available(第 4 列)(之前管道到 trsqueeze-repeas (-s) 表示空格):

You can get the Available (4th column) for example with awk or cut (previously piping to tr to squeeze-repeats (-s) for spaces):

$ df -k /tmp | tail -1 | awk '{print $4}'
2586456
$ df -k /tmp | tail -1 | tr -s ' ' | cut -d' ' -f4
2586456

和往常一样,如果您想将结果存储在变量中,请使用 var=$(command) 语法,如下所示:

As always, if you want to store the result in a variable, use the var=$(command) syntax like this:

$ myUsed=$(df -k /tmp | tail -1 | awk '{print $4}')
$ echo "$myUsed"
2586456

另外,来自 Tim Bunce 的评论 您可以使用 --direct 来处理长文件系统名称以获取 - ,这样它就不会打印破坏引擎的行:

Also, from the comment by Tim Bunce you can handle long filesystem names using --direct to get a - instead, so that it does not print a line that breaks the engine:

$ df -k --direct /tmp
Filesystem     1K-blocks    Used Available Use% Mounted on
-                7223800 4270396   2586456  63% /

这篇关于使用 df 获取可用磁盘空间以仅以 kb 为单位显示可用空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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