1

I know this has been asked before, and I have looked at the previous posts, but can't seem to get what I am trying to do working.

I know it's really basic, so I'm hoping this will be easy for most people on SO.

I want to create a simple bash script that pings an address, and then inserts the ping output into a csv file (or rather, into a file, separated with commas).

The ping command would be

ping -D google.com

and the output looks like

PING google.com (74.125.239.103) 56(84) bytes of data.
[1393992465.052723] 64 bytes from nuq05s01-in-f7.1e100.net (74.125.239.103): icmp_req=1 ttl=55 time=2.66 ms

I want to insert epoch time, ttl, and time into a file, separated by commas. If it's easy enough, then it wouldn't hurt to convert to the epoch time to a date also, but this can be my next step in this simple project.

I figured out the command to convert epoch time to human format is

date -d @[epoch_time]

Side trivia - why do I need the @?

2
  • Side trivia answer: that's the way the people who wrote date decided to recognize an epoch time. You can also pass arguments such as date -d 'now + 21 days'. Commented Mar 5, 2014 at 4:28
  • 1
    The @ avoids an ambiguity with epoch offsets for certain dates in the second half of August 1970. Commented Mar 5, 2014 at 4:35

1 Answer 1

1
ping -D google.com | sed -n -e 2p -e 2q |
while read epoch b64 bytes from host ip icmp ttl time ms
do
    date=$(date -d @$(sed 's/[][]//g' <<< "$epoch"))
    ttl=$(sed 's/ttl=//' <<< "$ttl")
    time=$(sed 's/time=//' <<< "$time")
    echo "$date,$ttl,$time"
done >> file.csv

Clearly, you can extend the number of lines you analyze by adjusting the first sed command. You can probably do the editing within the loop with ${var/x/y} notation, but I don't think of doing that until I'm writing up at the end because I've spent longer working with shells where that wasn't an option than I have with bash. Are you sure you don't want the host or IP address information?


In the cold light of morning, there's an easy way to improve the code:

ping -D google.com | sed -n -e 2p -e 2q |
while read epoch b64 bytes from host ip icmp ttl time ms
do
    epoch=${epoch#[}
    epoch=${epoch%]}
    date=$(date -d @${epoch})
    echo "$date,${ttl#ttl=},${time#time=}"
done >> file.csv

It's a matter of choice whether you create the date variable or simply embed the $(date -d @${epoch}) directly in the echo argument.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! I couldn't figure out how to use sed, awk, or grep, but I knew it could be done with each. I don't need the host information, it's just for monitoring our network. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.