sh 脚本在 while 循环中卡在读取命令上

sh script gets stuck on read command in while loop

我正在尝试编写一个脚本,我将把它放入我的 pi 的 cron 中,以每 10 秒检查一次网络连接,如果无法 ping 到 google,它将写入一个文本文件作为 false ,那么下次成功时会重启一个程序,因为具体的程序自动重连网络有问题

当我从同一目录中的终端执行脚本时,脚本似乎可以正常工作,然后我 cd 回到 / 并添加了一堆注释,现在它只是退出脚本而没有任何输出,并且对于我的生活,我无法弄清楚我在哪里搞砸了 - 我对脚本编写还比较陌生,所以我可能会在这里遗漏一些绝对明显的东西,但我在 google 上找不到任何有用的东西。

file heirarchy:
/home/pi/WEB_UI/
inside the WEB_UI folder are both of the scripts i'm running here.
nonet.sh - the script in question
pianobar.sh - a simple script to pkill a program and reload it after 5 seconds.
var.txt - a text file that will only ever contain "true" or "false

我试过删除所有评论,将文件位置更改为 ./ 并稍等片刻; do命令一行,但我无法弄清楚问题出在哪里。如果我 运行 sh -x 脚本,它 returns:

    pi@raspberrypi:~/WEB_UI $ sh -x nonet.sh
    + ping -q -c 1 -W 1 google.com
    + read line

有趣的是,我从我使用的测试脚本中得到了相同的结果,基本上是

"if var.txt says 'true', echo 'up', else echo 'down'" 
    #!/bin/sh

    #ping google, if successful return true
    if ping -q -c 1 -W 1 google.com >/dev/null; then
        #read variable line, perform action do
        while read line
        do
        #leading $ means return previous output. if line is false:
        if [ "$line" = "false" ]
        then
            #return network up text, run pianobar script, set var.txt to true.
            echo "the network is back up"
            sh /home/pi/WEB_UI/pianobar.sh
            echo true > /home/pi/WEB_UI/var.txt
        else
            #otherwise return network is up, set var.txt to true
            echo "the network is up"
            echo true > /home/pi/WEB_UI/var.txt
        #fi ends an if statement, done ends a while loop.
        #text after done tells the while loop where to get the line variable
        fi
        done < /home/pi/WEB_UI/var.txt
    else
        while read line
        do
        if [ "$line" = "false" ]
        then
            #if var.txt is already false, ping google again
            if ping -q -c 1 -W 1 google.com >/dev/null; then
                #if ping works, the network is back, restart pianobar, set var to true
                echo "the network is back up"
                sh /home/pi/WEB_UI/pianobar.sh
                echo true > /home/pi/WEB_UI/var.txt
            else
                #if var.txt is false, network is still down. wait.
                echo "the network is still down"
            fi
        else
            echo "the network is down"
            echo false > /home/pi/WEB_UI/var.txt
        fi
        done < /home/pi/WEB_UI/var.txt
    fi

脚本应该只回显一条简单的行,说明网络是正常运行、故障、备份还是仍然故障,这取决于它有多少标志passes/fails。如有任何帮助,我们将不胜感激!

正如 Shellter 在上面的评论中所说,问题是我需要在我的 var.txt

行的末尾添加 \n

I think I saw another post recently where while read... was frustrated by a missing \n char, so maybe you want to do printf "false\n" > file instead. Good luck.