1
#!/bin/sh
host google.com>/dev/null
while [  $? -ne 0 ];
do
sleep 3
done
say "You are now connected to internet"

I guess $? is associated with google.com>/dev/null, making the logic work, but i am interested in detail description on $?

Thanks in advance.

roshan
  • 160
  • 1
  • 7

1 Answers1

2

I know this will sound pedantic, but $? is not a variable, it is a value. ? is the name of the variable, placing $ at the front gives the value.

Now you can search for ? in man bash:

Expands to the exit status of the most recently executed foreground pipeline.

It is often tested unnecessarily. if and while statements in bash (and most shells) test for success(true) or failure(false). Success is where the value of ? is 0, and failure when it is some other number (which has the range 1-255). ! means "not", as in many languages, and inverts the truth:

while ! host google.com>/dev/null
do
    sleep 3
done
echo "You are now connected to internet"

(I had to use echo, not sure where say comes from, Perl?)

cdarke
  • 42,728
  • 8
  • 80
  • 84
  • 2
    Note that the example given in this answer changes the semantics of the code (it changes them to be correct). In the code of the question, the success of the `host` command is checked only once. Each subsequent evaluation of `$?` is checking the return status of `sleep`! – William Pursell Sep 10 '13 at 14:04
  • @cdarke unnecessary testing on while happened because of lack of knowledge on $?.. now i got it and thanks for making it clear . and one more thing, say is Mac Os X specific text to speech command.. – roshan Sep 10 '13 at 15:27