Bash – Shell script not able to awk created file

bash

I'm trying to create some simple pass/fail test scripts, but I am having some challenges as outlined below. My intent is to get the full results of a command (such as ping) into a results.txt file to keep, but also parse the results.txt file for different checks to raise if issues are detected:

#!/bin/bash
ping -c 20 google.com > results.txt
packetloss = `awk '/packet loss/{x=$6} END{print x}' results.txt`
echo "$packetloss" >> debug.txt
#  if packetloss > 0, add to an error.txt to fail
#  if avg ping time > 5ms, add to an error.txt to fail

The packetloss variable is not getting the awk information from the results.txt file (sending to a debug file to review). I was wondering if there is something about shell scripting that would prevent this and an associated workaround?

Manually running awk on results.txt returns '0%' which is the expected result.

Best Answer

Spaces are not allowed around =!

So:

#!/bin/bash
ping -c 20 google.com > results.txt
packetloss=$(awk '/packet loss/{print $6}' results.txt)
echo "$packetloss" >> debug.txt

Or even shorter:

ping -c 20 google.com |
    awk '/packet loss/{sub(/%/, "");print $6 >> "debug.txt"}'

NOTE:

  • There is no need to assign the x variable; you can print $6 directly.
  • AWK itself can create new files with its output
  • The backquote
    `
    is used in the old-style command substitution, for example :
foo=`command`

The foo=$(command) syntax is recommended instead. Backslash handling inside $() is less surprising, and $() is easier to nest.

Check http://mywiki.wooledge.org/BashFAQ/082

Extra solution using Perl:

ping -c 20 google.com |
    perl -lne '/(\d+)%\s+packet\s+loss/ and print $1' >> debug.txt
Related Question