2011年1月13日

挖掘 type 命令

今天测试个脚本,居然发现 ifconfig 命令会找不到,呖。。。。开发无止境,测试无止境!!

修改了一下,用 type 命令重新定位一下,判断系统中 ifconfig 命令的位置,代码如下:
IFCONF="/sbin/ifconfig"
[ ! -x "/sbin/ifconfig" ] &&
IFCONF=`type ifconfig | awk '{print $3}'`

接着又发现新问题了,type 的返回信息很“丰富”啊。。。
启动 bash 以后运行 type ifconfig 返回 ifconfig is /sbin/ifconfig
运行一次 ifconfig 后再运行 type ifconfig 返回 ifconfig is hashed (/sbin/ifconfig)

查看一下帮助,看看有没有什么参数可以用,type --help,
type: usage: type [-afptP] name [name ...]
不过,只有bash才支持这些参数;非POSIX的东西,不敢多用。

为了保证可靠性,修改代码:
IFCONF="/sbin/ifconfig"
[ ! -x "/sbin/ifconfig" ] &&
IFCONF=`type ifconfig | awk '{print $NF}' | sed 's/(\|)//g'`

当然,仍然不放心。。因为 type 有时候还会有这样的输出格式:
(bash) type type --> type is a shell builtin
(ksh) type type --> type is an alias for 'whence -v'

如果某人在环境变量里面 alias ifconfig='ifconifg -a' 了,这个脚本会报错吗?
好象不会,有兴趣可以研究一下。。。。。