把一段代碼整理到了一個小單元中,並給這個小單元起一個名字,當用到這段代碼時直接調用這個小單元的名字便可。python
函數就是一個子shell,就是一個代碼段,定義完函數就能夠引用它shell
格式:vim
格式: function f_name() { command } 函數必需要放在最前面
#!/bin/bash input(){ echo $1 $2 $0 $# } input 1 a b 9
[root@yong-01 shell2]# sh -x fun1.sh + input 1 a b 9 + echo 1 a fun1.sh 4 1 a fun1.sh 4
[root@yong-01 shell2]# sh -x fun1.sh + input 1 a b 9 + echo 1 a fun1.sh 4 1 a fun1.sh 4 [root@yong-01 shell2]# vim fun1.sh [root@yong-01 shell2]# sh fun1.sh 1 4 1 4 fun1.sh 2
#!/bin/bash sum() { s=$[$1+$2] #定義變量s = $1+$2 /其中 $1爲第一個參數,$2爲第二個參數 echo $s } sum 2 6 #輸出 第一個參數和第二個參數
[root@yong-01 shell2]# sh -x fun2.sh + sum 2 6 + s=8 + echo 8 8
#!/bin/bash ip() { ifconfig |grep -A1 "$eth: " |awk '/inet/ {print $2}' #查看網卡,過濾出ens33及下面的一行,匹配inet行並打印出第二段 } read -p "Please input the eth name: " eth myip=`ip $eth` echo "$eth address is $myip"
[root@yong-01 shell2]# ifconfig |grep -A1 "ens33" ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.180.134 netmask 255.255.255.0 broadcast 192.168.180.255 [root@yong-01 shell2]# ifconfig |grep -A1 "ens33"|tail -1 inet 192.168.180.134 netmask 255.255.255.0 broadcast 192.168.180.255 [root@yong-01 shell2]# ifconfig |grep -A1 "ens33"|tail -1|awk '{print $2}' 192.168.180.134
#!/bin/bash #coding:utf8 ip() { a=`ifconfig |grep -A1 "$eth: " |tail -1 |awk '{print $2}'` if [ -z "$a" ] then echo $eth echo "沒有這個網卡名" exit fi echo $a } read -p "請輸入你的網卡名字: " eth myip=`ip $eth` echo "$eth address is $myip"
seq 1 5
)[root@yong-01 shell]# b=(1 2 3) 定義數組 [root@yong-01 shell]# echo ${b[@]} 表示數組 1 2 3 [root@yong-01 shell]# echo ${b[*]} 表示數組 1 2 3
[root@yong-01 shell]# echo ${b[1]} 2 [root@yong-01 shell]# echo ${b[2]} 3 [root@yong-01 shell]# echo ${b[0]} 1
[root@yong-01 shell2]# echo ${#b[@]} 3 [root@yong-01 shell2]# echo ${#b[*]} 3
[root@yong-01 shell2]# echo ${b[*]} 1 2 3 [root@yong-01 shell2]# b[3]=aa [root@yong-01 shell2]# echo ${b[*]} 1 2 3 aa [root@yong-01 shell2]# b[3]=100 [root@yong-01 shell2]# echo ${b[*]} 1 2 3 100
[root@yong-01 shell2]# unset b[3] [root@yong-01 shell2]# echo ${b[*]} 1 2 3 [root@yong-01 shell2]# unset b 把數組的值清空 [root@yong-01 shell2]# echo ${b[*]}
[root@yong-01 shell2]# a=(`seq 1 10`) [root@yong-01 shell2]# echo ${a[*]} 1 2 3 4 5 6 7 8 9 10
3表示從3開始,4表示截取4個 [root@yong-01 shell2]# echo ${a[*]} 1 2 3 4 5 6 7 8 9 10 [root@yong-01 shell2]# echo ${a[*]:3:4} 4 5 6 7
[root@yong-01 shell2]# echo ${a[*]:0-3:2} 8 9
[root@yong-01 shell2]# echo ${a[*]} 1 2 3 4 5 6 7 8 9 10 [root@yong-01 shell2]# echo ${a[*]/8/6} 1 2 3 4 5 6 7 6 9 10
[root@yong-01 shell2]# a=(${a[*]/8/6}) [root@yong-01 shell2]# echo ${a[*]} 1 2 3 4 5 6 7 6 9 10