Shell 四

14.shell腳本中的函數

函數就是把一段代碼整理到了一個小單元中,並給這個小單元起一個名字,當用到這段代碼時直接調用這個小單元的名字便可。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}vim

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

從倒數第3個元素開始,截取2個數組

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

[root@feature1 ~]# echo ${a[@]:0-3:2}
3 4
  • 數組替換
echo ${a[@]/3/100}
a=(${a[@]/3/100})
相關文章
相關標籤/搜索