标准输出的问题

Problems with stdout

我正在设计 shell bash 脚本。它有很多功能,其中之一就是检测网卡是否处于监控模式。不确定是否有 "pro" 方法可以做到这一点。我的基本方法有效但有问题。是下一个功能:

function monitor() {

    WIFI="wlan0" #hardcoded wlan0 for the example
    mode=`iwconfig $WIFI|cut -d ' ' -f 6`

    if [[ $mode == "Mode:Monitor" ]]; then
        echo "Your interface $WIFI is in monitor mode already"
        return
    fi
    #Here is the rest of the function... not relevant
}

问题是在屏幕上打印命令的标准输出,我不想在屏幕上打印任何内容。所以我首先想到的是将标准输出重定向到 /dev/null 这样做:

mode=`iwconfig $WIFI|cut -d ' ' -f 6 > /dev/null 2>&1`

但如果我这样做,它就会停止工作...我想是因为它需要标准输出将一个命令通过管道传输到另一个命令才能工作。

如果我select 已经是监控模式的卡,一切正常。问题是如果网络接口不处于监控模式(例如 eth0),它会打印:

eth0 没有无线扩展。

如何使用管道的标准输出并防止在屏幕上打印任何内容?

提前致谢。

干杯。

不要在你的命令替换中包含 > /dev/null,因为它会阻止在变量 [=14= 中捕获 任何东西 ].

如果您的目的是在变量$mode:

中捕获stdout和silencestderr
mode=`iwconfig "$WIFI" 2>/dev/null | cut -d ' ' -f 6 `

如果您的意图是捕获两者 stdout 和 stderr,正如您的解决方案尝试建议的那样:

mode=`iwconfig "$WIFI" 2>&1 | cut -d ' ' -f 6 `

注意:正如@nsilent22 在评论和 中指出的那样, 2/dev/null2>&1 的位置在这里至关重要 iwconfig 可能会产生 stderr 输出,因此必须将重定向应用于 it,而不是 cut.

通常,如果您想将重定向应用到整个管道,您可以使用命令分组;例如:

mode=`{ iwconfig "$WIFI" | cut -d ' ' -f 6; } 2>/dev/null`

沉默 stderr 你的 iwconfig 命令(使用 2> /dev/null 重定向):

iwconfig $WIFI 2> /dev/null | cut -d ' ' -f 6