Bash 脚本使用 sed 将 df -h 可用磁盘空间与 aria2c 文件大小进行比较

Bash 脚本使用 sed 将 df -h 可用磁盘空间与 aria2c 文件大小进行比较

我正在尝试将 的输出aria2c -S与进行比较df -h

例如aria2c -S ../Radio* |grep 'Total Length'给出:

Total Length: 12GiB (13,191,069,983)

我想要比较一下,df -H / | tail -1 | awk '{print $4}'结果如下:

29G

所以类似这样,但单位正确。我猜用 sed 正则表达式来隔离 之前的数字G

#!/bin/bash
avail=$(df -H / | tail -1 | awk '{print $4}' | sed -r  's/^[^0-9]*([0-9]+).*/\1/')
filesize=$(aria2c -S ../file.zip |grep 'Total Length' | sed -r  's/^[^0-9]*([0-9]+).*/\1/')
if $avail < $filesize
echo "not enough free space"
else
aria2c $URL
fi

答案1

最好用字节来比较这两个数字。所以

#!/bin/bash
# get free disk space in KB 
avail_in_kb=$(df -BK / | tail -1 | awk '{print $4}' | sed -r  's/^[^0-9]*([0-9]+).*/\1/')

# get total size in bytes. \K for looking behind. (?=\)) for looking ahead. 
filesize_in_bytes=$(aria2c -S ../file.zip |grep -oP 'Total Length.*\(\K.*(?=\))'|tr -d ',')

# expression needs to be enclosed in brackets. -lt stands for less than. 
if [ "$((avail_in_kb*1024))" -lt "$filesize_in_bytes" ]
# keyword "then" is required. 
then
echo "not enough free space"
else
aria2c $URL
fi

相关内容