Search code examples
bashpingosx-elcapitan

Ping result to log script (El Capitan)


I'm working on a mac running El Capitan.

For a project I've been working on I'm trying to write a simple script to log ping times. I've come to the conclusion it isn't as simple as I'd thought. My first problem was "Ambiguous redirect" when using variables. I've corrected that, using quotes around variables, with help from $INPUT Ambiguous redirect

But now I get a different error when running the following script:

#!/bin/sh

set PINGDELAY=1.5
set PINGIP=google.nl
set PINGLOG=~/Library/Logs/doctorping.log

sudo ping -i "$PINGDELAY" "$PINGIP" | perl -nle 'use Time::Piece; BEGIN {$|++} print localtime->datetime, " ", $_' >> "$PINGLOG"

The error is

ping: invalid timing interval: `'

It's probably something I've overlooked but I'm a real noob when it comes to scripting and programming.

My goal isn't to process text or extract bits of it, it's just to monitor connections and have the results written to the log. It'd probably be wise to limit the number of log lines, but I'll get to that later. (of course would be appreciated if someone could point me in the right direction, but first things first)

Thanks!


Solution

  • The set command is not to set shell variables; it's used to set shell execution options and/or replace the script's argument list. Just leave it off. Also, it's best to use lowercase (or mixed-case) variable names to avoid accidentally using one of the variables that means something special to the shell. Here's what I get:

    #!/bin/sh
    
    pingdelay=1.5
    pingIP=google.nl
    pinglog=~/Library/Logs/doctorping.log
    
    sudo ping -i "$pingdelay" "$pingIP" | perl -nle 'use Time::Piece; BEGIN {$|++} print localtime->datetime, " ", $_' >> "$pinglog"