Issue
I have an R script that gets the public IP by
system("curl ifconfig.me",intern = T )
and then writes/appends it in a CSV file
write.table(data.frame(start.script=start.time, runtime=round(Sys.time()-start.time,4), ip=myip), append = T, file = "/home/eic/ip.report.csv", row.names = F,sep = ",", col.names = !file.exists("/home/eic/ip.report.csv"))
the script runs with cron every minute.
However, i will be running it in an small raspberry Zero and the installation of R is almost 500MB
is it possible to do this with bash?
The output should create or append a CSV file with (time and public IP as strings). If the internet is not reachable , "Internet not reachable" should be output. It doesn't necessarily have to do curl ifconfig.me
to check for internet connectivity . Checking for ping at 8.8.8.8
would be also an option. However it should output the public IP.
Thanks
Solution
msg=$(curl -s --max-time 3 icanhazip.com) ||
msg='Internet unreachable'
echo "$(date '+%Y-%m-%d %T %Z'),${msg:-Unkown}" >> /home/eic/ip.report.csv
Each line will look like:
2022-02-21 14:59:59,12.123.123.12 UTC
- Obviously, "Internet unreachable" means "icanhazip.com unreachable". Failing to
ifconfig.me
, and/orping -c 1 -W 3 google.com
to log connectivity, but not IP, may be worthwhile to reduce maintenance of an embedded device. - I might even use a 5 second time out (instead of 3), for very slow connections, like bad satellite, proxies, etc.
${msg:-Unkown}
replaces an empty response withUnkown
.- You can change the date format:
man date
. - Add
2>/dev/null
to curl if you don't want cron to log errors it may produce (eg if internet is down). - More info on checking internet connectivity from the shell: https://unix.stackexchange.com/questions/190513/shell-scripting-proper-way-to-check-for-internet-connectivity
Answered By - dan Answer Checked By - Timothy Miller (WPSolving Admin)