14.shell脚本中的函数

  • 格式:
function f_name()
{
        command
}
  • 函数必须要放在最前面
  • 示例1
#!/bin/bash
input() {
    echo $1 $2 $# $0
}

input 1 a b
[root@feature1 ~]# sh -x fun1.sh
+ input 1 a b
+ echo 1 a 3 fun1.sh
1 a 3 fun1.sh

  • 示例2
#!/bin/bash
sum() {
    s=$[$1+$2]
    echo $s
}
sum 1 2
[root@feature1 ~]# vim fun2.sh
[root@feature1 ~]# sh -x fun2.sh
+ sum 1 2
+ s=3
+ echo 3
3

  • 示例3
#!/bin/bash
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"
[root@feature1 ~]# sh -x fun3.sh
+ read -p 'Please input the eth name: ' e
Please input the eth name: enp0s3
++ ip enp0s3
++ grep -A1 'enp0s3: '
++ tail -1
++ awk '{print $2}'
++ ifconfig
+ myip=10.0.2.20
+ echo 'enp0s3 address is 10.0.2.20'
enp0s3 address is 10.0.2.20

[root@feature2 bin]# ifconfig |grep -A1 "enp0s3: "
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.200  netmask 255.255.255.0  broadcast 192.168.1.255
[root@feature2 bin]# ifconfig |grep -A1 "enp0s3: "|tail -l
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.200  netmask 255.255.255.0  broadcast 192.168.1.255
[root@feature2 bin]# ifconfig |grep -A1 "enp0s3: "| tail -l
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.200  netmask 255.255.255.0  broadcast 192.168.1.255
[root@feature2 bin]# ifconfig |grep -A1 "enp0s3: " | tail -1
        inet 192.168.1.200  netmask 255.255.255.0  broadcast 192.168.1.255

[root@feature2 bin]# ifconfig |grep -A1 "enp0s3: " | tail -1 |awk '{print $2}'
192.168.1.200


15.shell中的数组

  • 定义数组 a=(1 2 3 4 5); echo ${a[@]}
[root@feature1 ~]# a=(1 2 3 4 5);
[root@feature1 ~]# echo ${a[@]}
1 2 3 4 5

  • 获取数组的元素个数echo ${#a[@]}
[root@feature1 ~]# echo ${#a[@]}
5

  • 读取第三个元素,数组从0开始echo ${a[2]}
[root@feature1 ~]# echo ${a[0]}
1
[root@feature1 ~]# echo ${a[1]}
2
[root@feature1 ~]# echo ${a[2]}
3

  • 显示整个数组echo ${a[*]} 等同于 ${a[@]}
[root@feature1 ~]# echo ${a[*]}
1 2 3 4 5
[root@feature1 ~]# echo ${a[@]}
1 2 3 4 5
  • 数组赋值a[1]=100; echo ${a[@]}
[root@feature1 ~]# a[1]=100;
[root@feature1 ~]# echo ${a[@]}
1 100 3 4 5
[root@feature1 ~]# a[5]=2; echo ${a[@]}
1 100 3 4 5 2
# 如果下标不存在则会自动添加一个元素
  • 数组的删除unset a; unset a[1]
[root@feature1 ~]# unset a;
[root@feature1 ~]# echo ${a[@]}

[root@feature1 ~]# a=(1 2 3 4 5);
[root@feature1 ~]# unset a[1]
[root@feature1 ~]# echo ${a[@]}
1 3 4 5

  • 数组分片a=(seq 1 5)从第一个元素开始,截取3个echo ${a[@]:0:3}
[root@feature1 ~]# a=(`seq 1 5`)
[root@feature1 ~]# echo ${a[@]:0:3}
1 2 3

从第二个元素开始,截取4个echo ${a[@]:1:4}

[root@feature1 ~]# echo ${a[@]:1:4}
2 3 4 5

从倒数第3个元素开始,截取2个

echo ${a[@]:0-3:2}

[root@feature1 ~]# echo ${a[@]:0-3:2}
3 4

  • 数组替换
echo ${a[@]/3/100}
a=(${a[@]/3/100})
03-13 16:20