如果条件检查变量随时间变化,则猛击 [英] Bash if condition to check variable for changes over time
问题描述
想知道是否有可能将此逻辑(检查变量是否随时间变化并在true时运行循环)转换为bash if语句或while循环条件.我希望有这样的东西:
Wondering if it's possible to finagle this logic (checking a variable for changes over time and running a loop while true) into a bash if statement or while loop condition. I was hoping for something like:
var=$(du -h *flat*.vmdk)
var2=$(sleep 1 ; du -h *flat*.vmdk)
if [[ $var != $var2 ]]; then
while true
do
echo -ne $(du -h *flat*.vmdk)\\r
sleep 1
done
else
echo "Transfer complete"
fi
我也玩过while loop
,而不是没有运气的if then
.
I've also played with a while loop
, rather than an if then
with no luck.
while [ $var != $var2 ] ; do echo -ne $(du -h *flat*.vmdk)\\r ; sleep 1 ; done
但是我看到不可能吗?或者我遇到了问题,这些问题正在错误地扩展.我对任何解决方案都持开放态度,尽管我受到非常基本的Shell(ESXi Shell)的限制,其中可能不存在许多常见的unix/shell工具.
But I'm seeing that's not possible? Or I'm having issues where things are incorrectly getting expanded. I'm open to any solution, although I am limited by a very basic shell (ESXi Shell) where many common unix/shell tools may not be present.
推荐答案
您正在做while [ $var != $var2 ]
,但是从不更新任何这些变量..
You are doing while [ $var != $var2 ]
but never updating any of these variables ..
我会做类似的事情:
function get_size() {
echo $(du -h *flat*.vmdk)
}
var="$(get_size)"
sleep 1
var2="$(get_size)"
while [ $var != $var2 ]; do
var=$var2
var2="$(get_size)"
echo -ne "$(get_size)\\r"
sleep 1
done
echo "Transfer complete"
它的作用:
- 使用函数,因为当您必须在同一行中编写两次或更多次时,它会在您的大脑中触发我应该使它成为函数".
- 在
while
循环中更新$var
和$var2
,因此您不必每次都检查相同的精确值,而是检查最后一个值与当前值之间的差异. - 在代码中添加换行符,因为代码是由人而不是机器读取的,人类不喜欢单行代码:)
- Use a function, because when you have to write two times or more a same line, it should trigger a "I should make it a function" in your brain.
- Updating
$var
and$var2
within thewhile
loop, so you don't check the same exact values each time, but check diff between last value and current one. - Add newlines to your code, because code is done to be read by humans, not machines, humans does not likes one-liners :)
我还没有测试
这篇关于如果条件检查变量随时间变化,则猛击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!