Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo output of a piped command

I am trying to just echo a command within my bash script code.

OVERRUN_ERRORS="$ifconfig | egrep -i "RX errors" | awk '{print $7}'"
echo ${OVERRUN_ERRORS}

however it gives me an error and the $7 does not show up in the command. I have to store it in a variable, because I will process the output (OVERRUN_ERRORS) at a later point in time. What's the right syntax for doing this? Thanks.

like image 954
Shopean1951 Avatar asked Oct 12 '25 18:10

Shopean1951


1 Answers

On Bash Syntax

foo="bar | baz"

...is assigning the string "bar | baz" to the variable named foo; it doesn't run bar | baz as a pipeline. To do that, you want to use command substitution, in either its modern $() syntax or antiquated backtick-based form:

foo="$(bar | baz)"

On Storing Code For Later Execution

Since your intent isn't clear in the question --

The correct way to store code is with a function, whereas the correct way to store output is in a string:

# store code in a function; this also works with pipelines
get_rx_errors() { cat /sys/class/net/"$1"/statistics/rx_errors; }

# store result of calling that function in a string
eth0_errors="$(get_rx_errors eth0)"

sleep 1 # wait a second for demonstration purposes, then...

# compare: echoing the stored value, vs calculating a new value
echo "One second ago, the number of rx errors was ${eth0_errors}"
etho "Right now, it is $(get_rx_errors eth0)"

See BashFAQ #50 for an extended discussion of the pitfalls of storing code in a string, and alternatives to same. Also relevant is BashFAQ #48, which describes in detail the security risks associated with a eval, which is often suggested as a workaround.


On Collecting Interface Error Counts

Don't use ifconfig, or grep, or awk for this at all -- just ask your kernel for the number you want:

#!/bin/bash
for device in /sys/class/net/*; do
  [[ -e $device/statistics/rx_errors ]] || continue
  rx_errors=$(<"${device}/statistics/rx_errors")
  echo "Number of rx_errors for ${device##*/} is $rx_errors"
done
like image 173
Charles Duffy Avatar answered Oct 14 '25 22:10

Charles Duffy