Bash if 条件检查变量随时间的变化 [英] Bash if condition to check variable for changes over time

查看:28
本文介绍了Bash if 条件检查变量随时间的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否可以将此逻辑(检查变量随时间的变化并在为真时运行循环)转换为 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 循环,而不是没有运气的 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"

它的作用:

  1. 使用函数,因为当你必须在同一行写两次或更多次时,它应该会在你的大脑中触发我应该让它成为一个函数".
  2. while 循环中更新 $var$var2,这样你就不会每次都检查相同的确切值,而是检查上一个值和当前值之间的差异.
  3. 在你的代码中添加换行符,因为代码是供人类阅读的,而不是机器阅读,人类不喜欢单行:)
  1. 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.
  2. Updating $var and $var2 within the while loop, so you don't check the same exact values each time, but check diff between last value and current one.
  3. Add newlines to your code, because code is done to be read by humans, not machines, humans does not likes one-liners :)

我没有测试过

这篇关于Bash if 条件检查变量随时间的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆