LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash Script (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-769257/)

jcky 11-15-2009 03:45 AM

Bash Script
 
#!/bin/bash
# alive2.sh
# Checks to see if hosts 192.168.1.100-192.168.1.105 are alive
# Iterate through IP address
for n in {100..105};
do
host=192.168.1.$n
ping -c2 $host &> /dev/null
if [ $? = 0 ];
then
echo "$host is UP"
else
echo "$host is DOWN"
fi
done

What is the purpose of "if [ $? = 0 ];"?

I need your kind help.

;p

pixellany 11-15-2009 03:55 AM

"$?" is the return code from a command. "0" means the command executed successfully.

You could also do this:

Code:

if $(ping -c2 $host &> /dev/null); then
    do stuff
else
    do other stuff
fi


(Always use [CODE] tags to make code easier to read.)

stevenworr 11-16-2009 10:46 PM

I can't resist:

Code:

for n in {100..105}
do
    host=192.168.1.$n
    echo -n "$host is "
    ping -c2 $host > /dev/null 2>&1 && echo up || echo down
fi
done


pixellany 11-17-2009 06:54 AM

Quote:

Originally Posted by stevenworr (Post 3759533)
I can't resist:

Code:

for n in {100..105}
do
    host=192.168.1.$n
    echo -n "$host is "
    ping -c2 $host > /dev/null 2>&1 && echo up || echo down
fi
done


Nice!! (but take out the "fi")


All times are GMT -5. The time now is 07:54 AM.