0

我使用 getopts 获取 MAC 地址并通过日志文件 grep 该 MAC 地址。它看起来像这样:

#!/bin/bash

while getopts ":m:hx:" opt; do
  case $opt in
    m)
        cat /var/log/vmlog/Verimatrix.log | grep $OPTARG | grep VCAS080455
        cat /var/log/vmlog/Verimatrix.log | grep $OPTARG | grep VCAS080285
        cat /var/log/vmlog/Verimatrix.log | grep $OPTARG | grep VCAS080290
      ;;
    h)
        echo "./search_mac.sh -m <mac address> will filter the logs by mac address"
        echo "./search_mac.sh -h will print this message"
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

我想在使用该选项时将结果导出到文件-x

./search_mac.sh -m 00067B6D87F0 -x /home/nico/extract.txt

在这一点上,我不明白如何从 -x 获取论点以进入我的案例的 m) 部分。

一点帮助会很棒。

谢谢

4

1 回答 1

3

我认为最好的方法是将选项参数的值保存在 shell 变量中,然后在最后运行您的命令:

#!/bin/bash

m_arg=
x_arg=

while getopts ":m:hx:" opt; do
  case $opt in
    m) m_arg="$OPTARG" ;;
    x) x_arg="$OPTARG" ;;
    h)
        echo "./search_mac.sh -m <mac address> will filter the logs by mac address"
        echo "./search_mac.sh -h will print this message"
        exit 0
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

if [[ "$x_arg" ]] ; then
    exec > "$x_arg"          # redirect STDOUT to argument of -x
fi

< /var/log/vmlog/Verimatrix.log grep -- "$m_arg" | grep VCAS080455
< /var/log/vmlog/Verimatrix.log grep -- "$m_arg" | grep VCAS080285
< /var/log/vmlog/Verimatrix.log grep -- "$m_arg" | grep VCAS080290

那说。. . 这个选项对我来说似乎没什么用,因为-x /home/nico/extract.txt它的含义与> /home/nico/extract.txt. 我错过了什么吗?

于 2012-12-04T02:39:57.687 回答