I'm back to (very modest) scripting after 20+ years outside of that domain.
I'd like to write a small script that pings some IP addresses (some internal and wired, some internal over CPL, some external) to troubleshoot the instability of my network connectivity.
I do a single ping to each host, and if it's down, it adds a line to a file named host_.txt
I don't need alerting, just logging.
I've read many posts here, and my current script was leaning towards the below.
As you can see, I'm storing 2 (stupid and fake for now) IPs in variables $IP1 and $IP2. I don't want to duplicate the code for each ping, so I basically wanted to encapsulate it in a "for" loop and use the value of the "i" counter to point to the correct variable ( IP$i would then give me IP1, IP2, ...).
My problems/questions:
- If I concatenate "IP" with $i, I end up with the name of my variable: IP1, IP2, ... but how can I refer to the value of this variable?
- More in general, is this "while true" a good method to have the script running continuously, as "ping" would do without its "-c" parameter? Won't it use too much resources on my small Raspberry Pi?
- Would it be better to consider building a list or a table of IPs, and go through that list without requiring the storage of IPs into separate variables?
Any other recommendations are most welcome!
Many thanks
#!/bin/bash IP1=127.0.0.1 IP2=127.0.0.2 while true do
stamp=$(date +"%Y%m%d-%T")
for i in $(seq 1 2)
do
target=IP$i
ping -c1 -W10 $target
if [ $? -ne 0 ]; then echo $target "KO at" $stamp > host_$IP$i.txt ; else echo $IP$i "OK > at" $stamp ; fi
done
sleep 1 done
For info, I also tried this, without success..
#!/bin/bash
IP1="127.0.0.1"
i=1
echo IP$i
echo $(echo "IP";echo $i)
EDIT: For the sake of documentation, with focus on the initial issue: "If I concatenate "IP" with $i, I end up with the name of my variable: IP1, IP2, ... but how can I refer to the value of this variable?"
This technique is called "indirect" and is documented in stackoverflow.com/tags/bash/info
My solution was simply to do this:
for i in $(seq 1 2)
do
target="IP"$i
echo "${!target}"
#I can then do smth like ping -c1 -W10 ${!target}
done
Hope this helps others!