function name {
commands
}
示例1:
#! /bin/bash
function inp(){ //定义一个inp的函数
echo $1 $2 $3 $0 $#
}
inp 1 a 2 b //传入参数 //传入参数
运行结果
[root@xavi ~]# sh function1.sh
1 a 2 function1.sh 4
neme() {
commands
}
#!/bin/bash
sum() { //定义的函数名为sum
s=$[$1+$2]
echo $s
}
sum 1 2
运行
[root@xavi ~]# sh function2.sh
3
先从普通命令调试开始:
最终确定了有效命令为:
ifconfig |grep -A1 "ens33: " |awk ‘/inet/ {print $2}‘
函数:
#!/bin/bash
ip()
{
ifconfig |grep -A1 "$1: " |awk ‘/inet/ {print $2}‘
}
read -p "please input the eth name: "eth
ip $eth
运行结果:
[root@xavi ~]# sh funciton3.sh
please input the eth name: eth33
192.168.72.130
192.168.72.150
127.0.0.1
192.168.122.1
修改完整:
vim funciton3.sh
#!/bin/bash
ip()
{
ifconfig |grep -A1 "$eth " |awk ‘/inet/ {print $2}‘
}
read -p "please input the eth name: " eth
UseIp=`ip $eth`
echo "$eth adress is $UseIp"
运行结果:
[root@xavi ~]# sh funciton3.sh
please input the eth name: ens33:
ens33: adress is 192.168.72.130
[root@xavi ~]# sh funciton3.sh
please input the eth name: ens33:0:
ens33:0: adress is 192.168.72.150
[root@xavi ~]# b=(1 2 3 4) //定义一个数组a并赋值 1 2 3
[root@xavi ~]# echo ${b[*]} //注意输出a的值的格式
1 2 3 4
[root@xavi ~]# echo ${b[0]} //注意第一个其实是 b[0]开始
1
[root@xavi ~]# echo ${b[1]}
2
[root@xavi ~]# echo ${b[@]}
1 2 3 4
[root@xavi ~]# echo ${#b[@]} //获取数组的元素个数
4
[root@xavi ~]# echo ${#b[*]} //获取数组的元素个数
4
[root@xavi ~]# b[3]=a
[root@xavi ~]# echo ${b[3]}
a
[root@xavi ~]# echo ${b[*]}
1 2 3 a
[root@xavi ~]# b[4]=a
[root@xavi ~]# echo ${b[*]}
1 2 3 a a
[root@xavi ~]# unset b[2] //删除摸个数组元素
[root@xavi ~]# echo ${b[*]}
1 2 a a
[root@xavi ~]# unset b //删除整个数组
[root@xavi ~]# echo ${b[*]}
[root@xavi ~]# a=(`seq 1 10`)
[root@xavi ~]# echo ${a[*]}
1 2 3 4 5 6 7 8 9 10
[root@xavi ~]# echo ${a[@]:3:4} //从第数组a[3]开始,截取4个。
4 5 6 7
[root@xavi ~]# echo ${a[@]:0-3:2} //从倒数第三个数组开始,截取两个
8 9
[root@xavi ~]# echo ${a[@]/8/6} //把8换成6
1 2 3 4 5 6 7 6 9 10
原文地址:http://blog.51cto.com/12995218/2106422