写脚本遇到的问题(一)
2016-05-19 18:25
417 查看
本文记录了写这个脚本中出现的一些问题,问题主要出现在正则表达式匹配不准确导致。写一个脚本,要求:1、脚本具有-i和-I两个选项,optind.sh [-i ethenet | -I IP] 2、根据用户输入来输出相应信息 3、当用户用错选项输出帮助信息,如[-i inerface| -I ip]初步写完,测试时发现: 当./getinterface -i eth0,测试OK,可以输出相应的信息; 当./getinterface -i eth1,由于没有eth1,有相应的错误提示信息; 然而,当./getinterface -i eth时,应该有"wrong ethenet card",但是却出现了“eth: eth: error fetching interface information: Device not found”报错。修改前
#!/bin/bash
#Name: optind.sh
#Description:
#Author:
#Version: 0.0.1
#Date: 2016-05-12 10:02:22
#Usage:
show_ip() {
#judge whether eth exists.
if ! ifconfig | grep -o "^[^[:space:]]\{1,\}" | cut -d: -f 2 | grep $1 &> /dev/null; then
return 1
fi
echo -n "$1: "
ifconfig $1 | grep -o "inet addr:[0-9\.]\{7,\}" | cut -d: -f 2
}
show_eth() {
#judge whether ip exists.
if ! ifconfig | grep -o "inet addr:[0-9\.]\{7,\}" | grep $1 &> /dev/null; then
return 2
fi
echo -n "$1: "
ifconfig | grep -B 1 $1 | grep -o "^[^[:space:]]\{1,\}"
}
usage() {
echo "getinterface.sh [-i inerface| -I ip]"
}
case $1 in
-i | -I)
while getopts ":i:I:" opt;do
case $opt in
i)
show_ip $OPTARG
[ $? -ne 0 ] && echo "wrong ethenet card"
;;
I)
show_eth $OPTARG
[ $? -ne 0 ] && echo "wrong ip"
;;
*)
usage
;;
esac
done
;;
*)
usage
;;esac[/code] 经分析,ifconfig | grep -o "^[^[:space:]]\{1,\}" | cut -d: -f 2 | grep $1,“eth”是“eth0”的子集,此处应该对$1做单词完全匹配,使用grep -E "\b$1\b"即可(见修改1)对于ifconfig | grep -o "inet addr:[0-9\.]\{7,\}" | grep "$1\b",也做了相应的修改(见修改2)修改后
#!/bin/bash
#Name: getinterface.sh
#Description:
#Author:
#Version: 0.0.1
#Date: 2016-05-12 10:02:22
#Usage:
show_ip() {
#judge whether eth exists.
#修改1
if ! ifconfig | grep -o "^[^[:space:]]\{1,\}" | cut -d: -f 2 | grep -E "\b$1\b" &> /dev/null; then
return 1
fi
#print ip
echo -n "$1: "
ifconfig $1 | grep -o "inet addr:[0-9\.]\{7,\}" | cut -d: -f 2
}
show_eth() {
#judge whether ip exists.
#修改2
if ! ifconfig | grep -o "inet addr:[0-9\.]\{7,\}" | grep "$1\b" &> /dev/null; then
return 2
fi
echo -n "$1: "
ifconfig | grep -B 1 $1 | grep -o "^[^[:space:]]\{1,\}"
}
usage() {
echo "getinterface.sh [-i interface| -I ip]"
}
case $1 in
-i | -I)
while getopts ":i:I:" opt;do
case $opt in
i)
show_ip $OPTARG
[ $? -ne 0 ] && echo "wrong ethenet card"
;;
I)
show_eth $OPTARG
[ $? -ne 0 ] && echo "wrong ip"
;;
*)
usage
;;
esac
done
;;
*)
usage
;;
esac[/code]小插曲 将写好的脚本粘贴到vim编辑器中,出现了每一行都在上一行的基础上向后缩进了很多。分析 设置了set autoindent,启用了自动缩进,但上面的情况显然违反了设置这个选项的本意。经查资料,找到了解决办法。解决办法:1. 在拷贝前输入:set paste (这样的话,vim就不会启动自动缩进,而只是纯拷贝粘贴)2. 拷贝完成之后,输入:set nopaste (关闭paste)来自为知笔记(Wiz)
相关文章推荐
- Linux socket 初步
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- Scientific Linux 5.5 图形安装教程
- Linux 下无损图片压缩小工具介绍