Linux echo print命令,linux – 管道命令的Echo输出

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

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

echo ${OVERRUN_ERRORS}

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

解决方法:

关于Bash语法

foo="bar | baz"

…将字符串“bar | baz”赋给名为foo的变量;它没有运行吧|巴兹作为管道.为此,您希望以现代$()语法或过时的基于反引号的形式使用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相关联的安全风险,其通常被建议作为变通方法.

关于收集接口误差计数

根本不要使用ifconfig,grep或awk – 只需向内核询问您想要的数字:

#!/bin/bash

for device in /sys/class/net/*; do

[[ -e $device/statistics/rx_errors ]] || continue

rx_errors=$(

echo "Number of rx_errors for ${device##*/} is $rx_errors"

done

标签:bash,shell,unix,linux,echo

来源: https://codeday.me/bug/20190717/1487669.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值