管道命令的Echo输出

时间:2016-09-27 15:43:25

标签: linux bash shell unix echo

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

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

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

3 个答案:

答案 0 :(得分:7)

关于Bash语法

foo="bar | baz"

...分配字符串" bar |巴兹"到名为foo的变量;它不会将bar | baz作为管道运行。为此,您希望以现代$()语法或过时的基于反引号的形式使用command substitution

foo="$(bar | baz)"

存储以后执行的代码

由于你的意图不清楚 -

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

# 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)"

有关在字符串中存储代码的缺陷以及相同内容的替代方法的扩展讨论,请参阅BashFAQ #50。同样相关的是BashFAQ #48,它详细描述了与eval相关的安全风险,通常建议将其作为解决方法。

关于收集接口错误计数

根本不使用ifconfiggrepawk - 只需向内核询问您想要的号码:

#!/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

答案 1 :(得分:3)

使用$(...)来捕获命令的输出,而不是双引号。

overrun_errors=$(ifconfig | egrep -i "RX errors" | awk '{print $7}')

答案 2 :(得分:0)

RX errors周围的双引号是个问题。尝试;

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

要查看正在执行的命令,可以使用

set -v

set -x

例如;

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