Search code examples
macosapplescriptwake-on-lan

Apple script if while issiue


Hey guys my Applescript doesn't do what I expect. Where is my mistake?

try

set NAS to do shell script "ping -c 1 192.168.222.5"
if NAS contains "100.0% packet loss" then repeat until NAS contains "0% packet loss"
    do shell script "python /Users/Selim/Desktop/wol2.0.sh"
    set NAS to do shell script "ping -c 1 192.168.222.5"
end repeat
delay 20
tell application "Terminal" to activate
end try

I want ping to my NAS and when I don't get response I want to wake him up, but my script stops after send ping without response. Any idea what I am doing wrong? I want to send packets until the NAS wakes up.

I have changed the Code

try
do shell script "ping -c 1 192.168.222.5"
on error
set NAS to "100% packet loss"
repeat while NAS contains "100% packet loss"
    do shell script "python /Users/Selim/Desktop/wol2.0.sh"
    set NAS to do shell script "ping -c 1 192.168.222.5"
    if NAS contains "0% packet loss" then exit repeat

end repeat
say "Server startet, 20 sek"
delay 20
end try

tell application "Terminal" to activate

now i don't know how i get the loop to work with the on error command wich i get from the ping


Solution

  • Even if you have found the solution yourself there is no answer here so I try to complete it here. The string when we lay both strings on top of eachother we'll see "100.0%packet loss". As you can see when looking for "0% packet loss" it always will return true when you're sending just 1 packet. To be better safe than sorry you'd better match the entire line "1 packets transmitted, 1 packets received, 0.0% packet loss". Your first solution would be solved by changing the matches (also you can get rid if the if statement, if ping succeeds the first time the repeat will not run once):

    set NAS to do shell script "ping -c 1 192.168.222.5 || true"
    repeat until NAS contains "1 packets transmitted, 1 packets received, 0.0% packet loss"
        do shell script "python /Users/Selim/Desktop/wol2.0.sh"
        set NAS to do shell script "ping -c 1 192.168.222.5 || true"
    end repeat
    delay 20
    tell application "Terminal" to activate
    

    Update: A better version who does not match the printed string from ping but matches the returned number and coerce it into a boolean value.

    repeat until ping("192.168.222.5")
        do shell script "python /Users/Selim/Desktop/wol2.0.sh"
    end repeat
    delay 20
    tell application "Terminal" to activate
    
    on ping(IPNumber)
        return (do shell script "ping -t 1 -c 1 " & IPNumber & " >/dev/null && echo yes || echo no") as boolean
    end ping