BASH 问题来填充文件直到确定的大小
我编写了一个脚本来填充文件以进行一些磁盘容量测试。你能告诉我为什么我有错误吗?
#!/bin/bash
COUNTER=0;
FILE_SIZE_BITS=8589934592;
FILE_NAME="fill_me";
while [ $COUNTER -eq 0 ]; do
echo "Dummy text to fill the file" >> "$FILE_NAME";
SIZE='stat -c%s fill_me';
if [[ $SIZE -gt $FILE_SIZE_BITS ]]; then
let COUNTER=COUNTER+1;
fi
done
错误是:
-bash: [[: stat -c%s fill_me: division by 0 (error token is "fill_me")
谢谢
I wrote a script to fill a file for some Disk capacity testing. Could you please tell me why I have an error?
#!/bin/bash
COUNTER=0;
FILE_SIZE_BITS=8589934592;
FILE_NAME="fill_me";
while [ $COUNTER -eq 0 ]; do
echo "Dummy text to fill the file" >> "$FILE_NAME";
SIZE='stat -c%s fill_me';
if [[ $SIZE -gt $FILE_SIZE_BITS ]]; then
let COUNTER=COUNTER+1;
fi
done
the error is:
-bash: [[: stat -c%s fill_me: division by 0 (error token is "fill_me")
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
错误在这里:
请改为执行此操作:
这会将 SIZE 设置为 stat -c%s fill_me 命令的输出。
$(...)
语法是Command Substitution
语法:顺便说一句,你可以用
dd
[ 做同样的事情手册]:The error is here:
Do this instead:
This sets SIZE to the output of the
stat -c%s fill_me
command. The$(...)
syntax is theCommand Substitution
syntax:BTW you can do the same thing with
dd
[manual]:正如 amaud576875 回答的那样,
dd
是正确的选择。为了好玩,这里有另一种方法:
As amaud576875 answered,
dd
is the way to go.For fun, here's another method:
您已经发现了编程错误,但从 shell 编程的角度来看,整个脚本相当笨重。这是一个重构版本。
变量名称
COUNT
以及您对其执行的算术相当具有误导性,因为一旦 COUNT 大于 0,您就退出。在这种情况下,不妨使用 true/false 标志,但在这里,我什至不将状态存储在变量中。相反,当退出条件为 true 时,我break
跳出循环(从而跳出整个脚本)。You found the programming error already, but from a shell programming point of view, the overall script is quite clunky. Here is a refactored version.
The variable name
COUNT
and the arithmetic you performed on it is rather misleading, as you exit as soon as COUNT is bigger than 0. Might as well use a true/false flag in that case, but here, I don't even store the status in a variable. Instead, Ibreak
out of the loop (and thus, the entire script) when the exit condition is true.