LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Networking (https://www.linuxquestions.org/questions/linux-networking-3/)
-   -   Simple bash script (https://www.linuxquestions.org/questions/linux-networking-3/simple-bash-script-349329/)

lp449 08-02-2005 03:24 PM

Simple bash script
 
Hello,

I would need a simple script written in bash to be put in cron to be executed every five minutes. the script itself would have to grep DNS adresses from /etc/resolve.conf and then every five minutes ping one of them. If DNS responds then do nothing, otherwise it would have to execute folowing commands "rm /etc/dhcpc/dhcpcd-eth0.pid && dhcpcd -d eth0" Would someone help me to write it? I try to learn bash, but for now I don't know how to write such script but need it ...

rarsa 08-02-2005 04:03 PM

My recommendation?

Read a shell scripting tutorial like This one is very good. I followed it and I started writting scripts right away.

Start writting the script and send specific questions if you get stuck.

You will learn more and may even have fun in the process.

I also recommend as a general good development practice to start small and grow your script from there. Don't try to write all at once. Set a list of 'tasks' to implement and implement and test one by one, e.g.

1. Grep an address from resolve.conf

Write this part test it until it works. Once it's working go to the next item in the list.

2. Based on the grep result execute and echo command (the echo command is just a stub for the real code that will be added later)

Add this part, test your script until this works, then go to the next item in the list

3. Remove the pid files

Add this part, test your script

Etc...

This approach will allow you to learn the commands and play with them until you get the desired result.

Good luck.

(yes, yes, I know that this post was longer than writing the script, but I'm sure that will help you more)

maxut 08-02-2005 04:16 PM

Code:

#!/bin/bash

# reads every nameserver ip addr. and assign them to NS variable in a while loop.
cat /etc/resolv.conf|grep -i "nameserver"|awk -F " " '{ print $2 }'|while read NS ; do

# it pings each nameserver four times (ping -c 4) and then checks if all of 4 packets turns back.
if [ $(ping $NS -c 4 |grep "transmitted" | awk -F " " '{print $4}') -eq 4 ] ; then
echo "$NS: all of ping replies: ok"
else
echo "$NS: some or all of ping replies: failed"
fi
done

i hope it helps u.

good luck.


edit: if u have trouble with awk, try following:
awk -F "\ "
instead of
awk -F " "

lp449 08-02-2005 04:25 PM

Thank you all very much it helped me a lot :)


All times are GMT -5. The time now is 03:08 PM.