shell脚本中的函数, shell中的数组

shell脚本中的函数

  • 函数就是把一段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段代码时直接调用这个小单元的名字即可。
  • 格式:
    function f_name()
    {
    command
    }
  • 函数必须要放在最前面
示例1:
#!/bin/bash     #函数的使用;
input() {
    echo $1 $2 $# $0
}
input 1 a b

[root@second ~]# ./fun.sh 
1 a 3 ./fun.sh

示例2:
#!/bin/bash    #传递一个参数给函数;
input() {
    echo $n
}
read -p "please input:" n
input

[root@second ~]# ./fun.sh
please input:lksdfjs
lksdfjs
示例3:
#!/bin/bash
input () {
echo $1 $2 $3 $#    #传递三个参数到函数;
}
input $1 $2 $3

[root@second ~]# ./fun.sh adkkjl klsklj lkjljljss 
adkkjl klsklj lkjljljss 3
示例4
#!/bin/bash
sum() {			#实现两个参数相加;
    s=$[$1+$2]
    echo $s
}
sum $1 $2

[root@second ~]# bash fun2.sh 7 67786786
67786793
示例5:
#!/bin/bash    #输入网卡名,返回IP地址;
ip()          #求IP函数;
{
    ifconfig |grep -A1 "$1: " |tail -1 |awk '{print $2}'
}
read -p "Please input the eth name: " e   #交互,输入网卡名字;
myip=`ip $e`     #传递网卡名字给函数,求出并赋值;
echo "$e address is $myip"

Please input the eth name: ens33
ens33 address is 192.168.87.150
[root@second ~]# bash fun3.sh
Please input the eth name:  lo
lo address is 127.0.0.1

shell中的数组

[root@second ~]# a=(1 2 3 4 5);      #赋值一个数组;
[root@second ~]# echo ${a[@]}       #查看整个数组;
1 2 3 4 5
[root@second ~]# echo ${a[*]}        #查看整个数组;
1 2 3 4 5
[root@second ~]# echo ${a[1]}       #查看编号1的元素;
2
[root@second ~]# echo ${a[0]}      #查看编号0的元素;
1
[root@second ~]# a[1]=100           #对一个元素赋值;
[root@second ~]# echo ${a[1]}  
100
[root@second ~]# echo ${a[*]}
1 100 3 4 5
[root@second ~]# a[5]=6           #增加一个元素;
[root@second ~]# echo ${a[*]}    
1 100 3 4 5 6
[root@second ~]# echo ${a[5]}
6
[root@second ~]# unset a[5]      #删除一个元素;
[root@second ~]# echo ${a[5]}    

[root@second ~]# unset a        #删除整个数组;
[root@second ~]# echo ${a[*]}

[root@second ~]# a=(`seq 1 5`)    #使队列赋值数组;
[root@second ~]# echo ${a[*]}
1 2 3 4 5
[root@second ~]# echo ${a[*]:0:3}     #数组分片,编号0开始显示3个;
1 2 3
[root@second ~]# echo ${a[@]:2:2}    #编号2开始显示2个;
3 4
[root@second ~]# echo ${a[@]:0-2:2}   #倒数第二个开始显示2个;
4 5
[root@second ~]# echo ${a[*]}
1 2 3 4 5
[root@second ~]# echo ${a[@]/5/100}    #替换显示;
1 2 3 4 100
[root@second ~]# echo ${a[*]}				#内容没有变;
1 2 3 4 5
[root@second ~]# a[5]=5           #增加元素;
[root@second ~]# echo ${a[*]}
1 2 3 4 5 5
[root@second ~]# a=(${a[@]/5/100})     #替换赋值,所有的5都变成100;
[root@second ~]# echo ${a[*]}
1 2 3 4 100 100
发布了125 篇原创文章 · 获赞 5 · 访问量 4628

猜你喜欢

转载自blog.csdn.net/tanyyinyu/article/details/103179566