1.第一个案例:
[root@weixing01 shell]# sh fun1.sh
the first par is b
the second par is a
the third par is 2
the script name is fun1.sh
the number of par is 5
[root@weixing01 shell]# cat fun1.sh
#!/bin/bash
function inp(){
echo "the first par is $1"
echo "the second par is $2"
echo "the third par is $3"
echo "the script name is $0"
echo "the number of par is $#"
}
inp b a 2 3 adf
也可以把参数放在外面
[root@weixing01 shell]# cat fun1.sh
#!/bin/bash
function inp(){
echo "the first par is $1"
echo "the second par is $2"
echo "the third par is $3"
echo "the script name is $0"
echo "the number of par is $#"
}
inp $1 $2 $3
[root@weixing01 shell]# sh fun1.sh 1 2
the first par is 1
the second par is 2
the third par is
the script name is fun1.sh
the number of par is 2
2.第二个案例:
[root@weixing01 shell]# cat fun2.sh
#!/bin/bash
sum(){
s=$[$1+$2]
echo $s
}
sum 1 10
[root@weixing01 shell]# sh fun2.sh
11
[root@weixing01 shell]# sh -x fun2.sh
+ sum 1 10
+ s=11
+ echo 11
11
3.第三个案例:
[root@weixing01 shell]# cat fun3.sh
#!/bin/bash
ip()
{
ifconfig |grep -A1 "$1: "|awk ‘/inet/ {print $2}‘
}
read -p "please input the eth name: " eth
ip $eth
[root@weixing01 shell]# sh fun3.sh
please input the eth name: ens33
192.168.188.130
[root@weixing01 shell]# sh fun3.sh
please input the eth name: ens33:0
192.168.188.150
[root@weixing01 shell]# sh fun3.sh
please input the eth name: ens37
192.168.252.128
1.定义数组并打印:
[root@weixing01 shell]# b=(1 2 3)
[root@weixing01 shell]# echo $b
1
[root@weixing01 shell]# echo ${b[@]}
1 2 3
[root@weixing01 shell]# echo ${b[*]}
1 2 3
[root@weixing01 shell]# echo ${b[1]}
2
[root@weixing01 shell]# echo ${b[0]}
1
[root@weixing01 shell]# echo ${b[2]}
3
2.获取数组元素个数:加个#
[root@weixing01 shell]# echo ${#b[*]}
3
3.数组赋值:
[root@weixing01 shell]# b[3]=a
[root@weixing01 shell]# echo ${b[*]}
1 2 3 a
[root@weixing01 shell]# b[3]=66
[root@weixing01 shell]# echo ${b[*]}
1 2 3 66
4.如果下标不存在,自动添加一个:
[root@weixing01 shell]# b[5]=6
[root@weixing01 shell]# echo ${b[*]}
1 2 3 66 6
5.删除元素:
[root@weixing01 shell]# unset b[3]
[root@weixing01 shell]# echo ${b[*]}
1 2 3 6 6
[root@weixing01 shell]# unset b[4]
[root@weixing01 shell]# echo ${b[*]}
1 2 3 6
[root@weixing01 shell]# unset b
[root@weixing01 shell]# echo ${b[*]}
6.数组分片:
[root@weixing01 shell]# a=(`seq 1 10`)
[root@weixing01 shell]# echo ${a[*]}
1 2 3 4 5 6 7 8 9 10
[root@weixing01 shell]# echo ${a[*]:3:4}
4 5 6 7
[root@weixing01 shell]# echo ${a[*]:-3:2}
1 2 3 4 5 6 7 8 9 10
[root@weixing01 shell]# echo ${a[*]:0-3:2}
8 9
7.数组替换:
[root@weixing01 shell]# echo ${a[*]/8/6}
1 2 3 4 5 6 7 6 9 10
[root@weixing01 shell]# a=(${a[*]/8/6})
[root@weixing01 shell]# echo ${a[*]}
1 2 3 4 5 6 7 6 9 10
原文地址:http://blog.51cto.com/13517254/2105984