【问题标题】:nslookup capture stderr in a variable and displaynslookup 在变量中捕获 stderr 并显示
【发布时间】:2013-05-07 14:02:04
【问题描述】:

在一个 shell 脚本中,我正在对 URL 数量运行 nslookup

有时某些 url 返回无法解决错误。我需要在变量中捕获这些错误。

这里是 nslookup 的代码,它会返回 IP 地址

output=$(nslookup "$URL" | grep Add | grep -v '#' | cut -f 3 -d ' ' | awk 'NR>1' )

现在在同一个变量输出中,我想捕获错误

nslookup: can't resolve

Stdout 我在一个文件中捕获。

我尝试了不同版本的重定向 - 2>&1 和其他版本,但错误没有分配给变量。我不希望将错误重定向到单独的文件,但希望将其记录在上面的输出变量中。

【问题讨论】:

  • 您将2>&1 重定向放在"$URL" 之后和第一个管道之前?应该管用。祝你好运。
  • @shellter 这仅在 2>&1 之后没有其他管道时才有效
  • 应该可以。您使用的是什么操作系统?为了实用起见,@Jens 解决方案对我来说看起来不错。祝大家好运。

标签: shell stderr nslookup


【解决方案1】:

只要你使用 awk,就可以大大简化事情

nslookup "$URL" 2>&1 | 
awk -e '/Add/ && !/#/ && NR > 1 {print $2}' 
    -e '/resolve|NXDOMAIN/ { print "error" }'

为了清楚起见,将一行分成三行。我无法重现您所说的2&>1 的问题,我也不认为它应该会失败。

【讨论】:

    【解决方案2】:

    stderr 的重定向在你使用时起作用

    output=$(nslookup "$URL" 2>&1 | grep Add | grep -v '#' | cut -f 3 -d ' ' | awk 'NR>1')
    

    但这是徒劳的,因为您立即使用grep Add 将其过滤掉。你需要重新思考你的逻辑和你真正想要的东西。也许更好的方法是

    output=$(nslookup "$URL" 2>&1)
    case $output in
       (nslookup:*) ;;
       (*) output=$(echo "$output" | grep Add | ...);;
    esac
    

    【讨论】:

    • 感谢您的回复。会试一试的。
    猜你喜欢
    • 2012-06-17
    • 2014-10-05
    • 1970-01-01
    • 2014-08-05
    • 2012-06-20
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多