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