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

标签 bash fedora

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

相关文章:

linux - 如何通过在 Jenkins 中使用 bash 脚本读取 pid 文件来终止进程?

php - 通过 PHP 创建 FTP 用户

android - 无法在 Linux 上启动 Android 设备模拟器

python - Fedora 19 Pyclewn 找不到GDB版本

bash - AWS 配置 Bash One Liner

bash - 询问时如何在 bash 脚本中自动按 Enter?

bash - 在 shell 脚本中正确使用 bc 吗?

linux - 新建文件夹权限问题

python - Visual Studio Code Python 中的 "Assertion ' __builtin_expect(__n < this->size(), true) ' failed"错误

docker - 运行docker-compose up时的“dial unix/tmp/docker.sock: connect: permission denied”