bash 脚本中的简单数学计算
simple mathematical calculation in bash script
我在这里阅读了很多帮助主题,但从未找到关于我的具体问题的答案。
我在 red hat 7 中有这个 bash 代码(这并不重要,但是..)
if [[ $(stat -c %s) -gt 1024 ]];
then
echo " $(scale=1;stat -c %s log.txt / 1024) KiloBytes"
else
echo " $(stat -c %s log.txt) Bytes"
fi
它抛出这个错误:
stat: missing operand
Try 'stat --help' for more information.
0 Bytes
通过这个微小的检查,我想看看 log.txt 是否大于 1024 字节,如果为真,则将总字节大小除以 1024 并将输出回显为 XXXX 千字节。但是我错过了什么。 Shellcheck.com 表示一切正常...
谁能帮我解决这个问题?
您缺少文件名。你可能想要
if [[ $(stat -c %s log.txt) -gt 1024 ]];
# look: ^^^^^^^
成为您的第一行。如果您按照指示输入 stat --help
,它会告诉您正确的用法是
Usage: stat [OPTION]... FILE...
Display file or file system status.
-c %s
是选项,您没有在第一行指定任何文件。
您似乎缺少对 bc
的调用,这是一个用于 floating-point 算术的程序。 scale=1
通常是 bc
:
输入的一部分
# No
echo " $(scale=1;stat -c %s log.txt / 1024) KiloBytes"
# Yes - broken down into steps for easy reading
size=$(stat -c %s log.txt)
result=$(echo "scale=1; $size / 1024" | bc)
echo " $result KiloBytes"
也许您有兴趣减少脚本的大小:
stat -c %s log.txt | awk '{ print ([=10=] > 1024 ? [=10=] / 1024 " Kilobytes" : [=10=] " bytes") }'
使用 awk 解析 stat
的输出并打印字节或千字节,具体取决于大小。
我在这里阅读了很多帮助主题,但从未找到关于我的具体问题的答案。
我在 red hat 7 中有这个 bash 代码(这并不重要,但是..)
if [[ $(stat -c %s) -gt 1024 ]];
then
echo " $(scale=1;stat -c %s log.txt / 1024) KiloBytes"
else
echo " $(stat -c %s log.txt) Bytes"
fi
它抛出这个错误:
stat: missing operand
Try 'stat --help' for more information.
0 Bytes
通过这个微小的检查,我想看看 log.txt 是否大于 1024 字节,如果为真,则将总字节大小除以 1024 并将输出回显为 XXXX 千字节。但是我错过了什么。 Shellcheck.com 表示一切正常...
谁能帮我解决这个问题?
您缺少文件名。你可能想要
if [[ $(stat -c %s log.txt) -gt 1024 ]];
# look: ^^^^^^^
成为您的第一行。如果您按照指示输入 stat --help
,它会告诉您正确的用法是
Usage: stat [OPTION]... FILE...
Display file or file system status.
-c %s
是选项,您没有在第一行指定任何文件。
您似乎缺少对 bc
的调用,这是一个用于 floating-point 算术的程序。 scale=1
通常是 bc
:
# No
echo " $(scale=1;stat -c %s log.txt / 1024) KiloBytes"
# Yes - broken down into steps for easy reading
size=$(stat -c %s log.txt)
result=$(echo "scale=1; $size / 1024" | bc)
echo " $result KiloBytes"
也许您有兴趣减少脚本的大小:
stat -c %s log.txt | awk '{ print ([=10=] > 1024 ? [=10=] / 1024 " Kilobytes" : [=10=] " bytes") }'
使用 awk 解析 stat
的输出并打印字节或千字节,具体取决于大小。