【shell一天一练】网卡ip匹配练习,复习grep和awk命令

86 阅读2分钟

今日小练题目📢

写一个脚本可以接受选项[i,I],完成下面任务:

1)使用以下形式:xxx.sh [-i interface | -I ip]

2)当使用-i选项时,显示指定网卡的IP地址; 当使用-I选项时,显示其指定ip所属的网卡。 例:sh xxx.sh -i ens160 sh xxx.sh -I 192.168.0.1

3)当使用除[-i | -I]选项时,显示[-i interface | -I ip]此信息。

4)当用户指定信息不符合时,显示错误。(比如指定的eth0没有,而是eth1时)

优秀作业🤌🏻

#!/bin/bash
#author:xYLiuuuuuu
#date:2024-12-17

useage()
{
        echo "Please useage: $0 -i 网卡名字 or $0 -I ip地址"
}

if [ $# -ne 2 ]
then
        useage
        exit
fi

ip add |awk -F ":" '$1 ~ /^[1-9]/ {print $2}' |sed 's/ //g' > /tmp/eths.txt

[ -f /tmp/eth_ip.log ] && rm -f /tmp/eth_ip.log

for eth in `cat /tmp/eths.txt`
do
        ip=`ip add|grep -A2 ": $eth"|grep inet |awk '{print $2}' |cut -d '/' -f 1`
        echo "$eth:$ip" >> /tmp/eth_ip.log
done

del_tmp_file()
{
        [ -f /tmp/eths.txt ] && rm -f /tmp/eths.txt
        [ -f /tmp/eth_ip.log ] && rm -f /tmp/eth_ip.log
}

wrong_eth()
{
        if ! awk -F ':' '{print $1}' /tmp/eth_ip.log | grep -qw "^$1$"
        then
                echo "请指定正确的网卡名字"
                del_tmp_file
                exit
        fi
}

wrong_ip()
{
        if ! awk -F ':' '{print $1}' /tmp/eths.txt |grep -qw "^$1$"
        then
                echo "请指定正确的ip"
                del_tmp_file
                exit
        fi
}

case $1 in
        -i)
        wrong_eth $2
        grep -w $2 /tmp/eth_ip.log |awk -F ':' '{print $2}'
        ;;

        -I)
        wrong_ip $2
        grep -w $2 /tmp/eth_ip.log |awk -F ':' '{print $1}'
        ;;

        *)
        useage
        del_tmp_file
        exit
        ;;
esac

del_tmp_file

敲黑板📝

  • ip add |awk -F ":" '{print $1}'ip add的输出逐行以冒号分隔后打印第一个字段的内容。
  • grep -A2 ": docker0"里的-A2参数表示在匹配到包含 “: docker0” 的行之后,同时打印出其后的 2 行内容。
  • grep -w pattern file 会在文件中查找完整的单词与给定的 pattern 相匹配的行。
  • grep的-q参数仅仅以退出状态来表示是否找到了匹配的内容。如果找到了匹配,grep 以 0 状态退出;如果没有找到匹配,以 1 状态退出。脚本中常用于进行条件判断。
  • cut命令常用参数: -d指定分隔符 -f以字段为单位分割。
  • awk不指定分隔符默认是以空格为分割。
  • 边写脚本边调试get。
  • 临时文件可以大大降低写shell脚本的难度,但不要忘记在脚本执行结束时删除掉。
  • 巧用函数,减少冗余代码。
  • 选项参数用case实现
  • “>” 会覆盖目标文件原有内容进行写入,而 “>>” 会在目标文件原有内容的末尾进行追加写入。