如何将字符串转换为 Bash 以内的整数?

How can I convert a string to an integer within Bash?

我正在尝试创建一个 cronjob,它将 运行 取决于特定文件夹的磁盘使用输出。在我的测试环境中,我有一个名为 "Test" 的文件夹,大小为 4.0 KB。我正在查询它的大小:

du -csh /home/<username>/Test | grep total | cut -f1 | tr -d 'K'

输出分配给一个名为 DISK_SPACE 的变量,并留给我 4.0。我不知道如何将 4.0 转换为整数以满足以下条件:

if [ $DISK_SPACE -gt 3.0 ]
then
rm -rf /home/<username>/Test/*.*
else
echo $DISK_SPACE "is less than 3.0K and as a result the contents of the folder will NOT be deleted."

我的完整 bash 文件如下所示:

#!/bin/bash
DISK_SPACE=$(du -csh /home/<username>/Test | grep total | cut -f1 | tr -d 'K')
echo $DISK_SPACE
if [ $DISK_SPACE -gt 3.0 ]
then
rm -rf /home/<username>Test/*.*
else
echo $DISK_SPACE "is less than 3.0K and as a result the contents of the folder will NOT be deleted."
fi

我在 运行 之后收到的错误是:

4.0: integer expression expected

使用 printf 将您的实数四舍五入为整数。

printf "%1.0f\n" 4.0
4

printf "%1.0f\n" 4.6
5

请参阅 printf 联机帮助页。

以你为例,你可以这样做:

DISK_SPACE=4.0
DISK_SPACE=$(printf "%1.0f" ${DISK_SPACE})
echo ${DISK_SPACE}
4

du -h 打印供人类使用的数字。脚本不应使用 -h。尝试使用 -k-b 来获取易于解析的整数:

-k     like --block-size=1K

-b, --bytes
       equivalent to '--apparent-size --block-size=1'

Bash 不支持浮点运算。如果你只关心第一个数字是否大于3,你可以简单地trim任意小数。

if [ "${disk_space%.*}" -gt 3 ]; then ...

如果你需要适当的浮点数比较,也许实际上use a tool which supports floating-point arithmetic.

更简单

另请注意,我将您的变量转换为小写。你should not use all-uppercase names for your private variables.

除了 John Kugelman 的回答外,我还更改了以下行:

原文:

if [ $DISK_SPACE -gt 3.0 ]

新:

if [ $DISK_SPACE -gt 3072 ]

这使得 John 推荐的更改可以更好地与脚本一起工作:

du -csb /home/<username>/Test | grep total | cut -f1