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

问题描述 投票:1回答:1

[我正在尝试编写一个脚本,每10秒将其放入pi的cron中以检查网络连接,如果无法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

我已经尝试删除所有注释,将文件位置更改为./并花了一段时间;做命令单行,但我不知道问题出在哪里。如果我为脚本运行sh -x,它将返回:

    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'" 
  • 我想知道我的sh解释器是否有问题?
    #!/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

脚本应该仅回显一条简单的行,说明网络是处于启动,关闭,备份还是关闭的状态,这取决于它传递/失败的标志数量。任何帮助将不胜感激!

sh raspberry-pi3 raspbian
1个回答
0
投票

正如Shellter在上述评论中所说,问题是我需要在\ var.txt的行末添加\ n

[我想我最近看了另一篇文章,读的时候...由于缺少\ n字符而感到沮丧,所以也许您想改用printf“ false \ n”>文件。祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.