管道命令的Echo输出

Sho*_*951 3 unix linux bash shell echo

我试图在我的bash脚本代码中回显一个命令.

OVERRUN_ERRORS="$ifconfig | egrep -i "RX errors" | awk '{print $7}'"
echo ${OVERRUN_ERRORS}
Run Code Online (Sandbox Code Playgroud)

但是它给了我一个错误,$ 7没有显示在命令中.我必须将它存储在变量中,因为我将在稍后的时间点处理输出(OVERRUN_ERRORS).这样做的正确语法是什么?谢谢.

Cha*_*ffy 7

关于Bash语法

foo="bar | baz"
Run Code Online (Sandbox Code Playgroud)

...将字符串 "bar | baz"赋给名为的变量foo; 它不bar | baz作为管道运行.为此,您希望以现代语法或过时的基于反引号的形式使用命令替换$():

foo="$(bar | baz)"
Run Code Online (Sandbox Code Playgroud)

关于存储以后执行的代码

由于你的意图在问题中不明确 -

存储代码的正确方法是使用函数,而存储输出的正确方法是使用字符串:

# 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)"
Run Code Online (Sandbox Code Playgroud)

有关在字符串中存储代码的缺陷以及相同的替代方法的扩展讨论,请参阅BashFAQ#50.另外相关的是BashFAQ#48,它详细描述了与a相关的安全风险eval,这通常被建议作为一种解决方法.


关于收集接口误差计数

不要使用ifconfig,或者grep,或者awk为这个在所有-只问你的内核,你要的号码:

#!/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
Run Code Online (Sandbox Code Playgroud)