gpt4 book ai didi

bash - 如何在 Bash 中将字符串转换为整数?

转载 作者:行者123 更新时间:2023-11-29 09:45:26 27 4
gpt4 key购买 nike

我正在尝试创建一个 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

最佳答案

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

-k     like --block-size=1K

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

关于bash - 如何在 Bash 中将字符串转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55247781/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com