shell脚本以.sh为后缀,执行于linux或unix环境下,执行命令有./shellname.sh,sh shellname.sh, bash shellname.sh等。以./为执行方法时,实际上是试用shell中第一行指定的shell进行执行,如下所示。其中-e代表若shell脚本执行出错则推出脚本。若要调试脚本,可以在e后面加x参数,控制台会单步显示执行结果。
#!/bin/bash -e
shell脚本中不会识别windows的换行符\r,在windows编辑脚本时需要将windows的换行符\r\n改为\n。
变量或者字段中包含空格的话,需要用“”将其包起来,防止shell将空格分隔的变量或字段识别为多个参数,如:
if [ ! -z "`ifconfig | grep addr:$IP\ \ Bcast`" ] || [ ! -z "`ip addr | grep $IP/`" ]; then
echo "$IP"
return
fi
-z表示为空时返回true;-n不为空时返回true。
shell命令返回本机的IP地址:
[root@localhost ~]# ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:0C:29:5A:49:D1
inet addr:10.128.8.211 Bcast:10.128.8.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe5a:49d1/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:579283 errors:0 dropped:0 overruns:0 frame:0
TX packets:370502 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:53162799 (50.6 MiB) TX bytes:35862918 (34.2 MiB)
[root@localhost ~]# ifconfig eth0|grep "inet addr"
inet addr:10.128.8.211 Bcast:10.128.8.255 Mask:255.255.255.0
[root@localhost ~]# ifconfig eth0|grep "inet addr"| awk '{print $2}'
addr:10.128.8.211
[root@localhost ~]# ifconfig eth0|grep "inet addr"| awk '{print $2}'| awk -F: '{print $2}'
10.128.8.211