我使用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部分。
一点帮助就会很棒。
由于
答案 0 :(得分:3)
我认为最好的方法是在shell变量中保存option-arguments的值,然后在最后运行命令:
#!/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
的含义相同。我错过了什么吗?