Shell脚本知识整理

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值