Skip to main content
edited tags; edited tags
Link
Gilles 'SO- stop being evil'
  • 865.4k
  • 205
  • 1.8k
  • 2.3k
Source Link
aguywithsocks
  • 303
  • 1
  • 2
  • 6

waiting for network in a bash script

I'm running a script that relies on network being up and a network share be mounted. The script runs on login (which happens automatically after boot). The problem is that by the time the script runs, I usually do not have an IP address yet (DHCP). At the moment I just sleep the script for 15s, but I don't like this approach at all, since I want to be able to tell the user if something is wrong.

What my plan is, is loop while I don't have an IP address yet and continue when I do. Crucially, it has to time out after a while. What I came up with is to if [ ifconfig | grep "192.168.100" ]; but what happens is that grepconsumes the ]; and doesn't like it. Then bash also gets upset, because it can't find the ]; which grep ate. And then I haven't even implemented the time-out.

Someone suggested keeping a variable, and sleeping for, say, a second in each iteration and increase this variable each time. Here is my complete (non working) script (I'm fairly new to bash scripting):

x=0
while [ ifconfig | grep "192.168.100." > /dev/null ]; do
    echo "no nework"
    if "$x" -gt 200; then
        #Time out here
        exit 1
    x=$((x+1))
    sleep .1
    fi
done

#continue with rest of script...

Any pointers in the right direction would be greatly appreciated!