I wrote this bash script to have a notification when internet becomes accessible but I don't understand many of things that are happening. Here is the script:
while ! ping 8.8.8.8 -c 1 2&> /dev/null ; do true; done;
-c 1 option tells ping that i want to send only one packet.2&> /dev/null is there because i don't want to see output.true is there because bash didn't accept the do; syntax.! ping ... because ping returns non zero status code when no packet is received before some timeout.The intended behavior was for this loop to end when ping succeeds and the terminal emulator will automatically send me a notification.
ctrl + C doesn't work. I think it's killing the sub-command ping instead of the whole command.2&> /dev/null makes every thing works except for the minor issue that it writes output to the terminal.ctrl + C?2&> /dev/null make it work?Note that I already have a turnaround. Nevertheless I want to understand bash a little more.
f() { while ! ping 8.8.8.8 -c 1 ; do true; done; }; f 2&> /dev/null
The correct redirection operator is &>, not 2&>. The 2 is parsed as a separate argument to ping, and since pinging 2 never succeeds, the loop never exists.
Something I usually do in that kind of loops is adding a sleep command instead of true:
while ! ping 8.8.8.8 -c 1 &> /dev/null ; do sleep 1; done;
In that way you can use Ctrl+C while in the sleep and cancel the whole loop.
I think the better way is to setup Timeout in the ping.
while ! ping -c 1 -W 2 8.8.8.8 >/dev/null 2>&1 ; do sleep 1 ; done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With