函數的作用
1)命令的集合 完成特定功能的代碼塊
2)函數的優勢可以使代碼完全的模塊化 便於復用 加強可讀 易於修改
3)函數和變量類似 先定義才可調用,如果定義不調用則不執行
定義函數
函數的傳參
函數內的變量
返回值 return
定義函數
#!/bin/sh fun1(){ echo "第一種定義方式" } function fun2 { echo "第二種定義方式" } function fun3() { echo "第三種定義方式" } fun1 # 調用函數非常簡單 只需要寫函數名即可 fun2 fun3
函數傳參
1)函數名稱后面跟字符串傳參
[root@shell day5]# cat fun.sh #!/bin/sh fun(){ if [ -f $2 ];then echo "$2 exists" else return 5 fi } fun /etc/hosts /etc/passwd
2)使用腳本的參數傳參
[root@shell day5]# cat fun.sh #!/bin/sh fun(){ if [ -f $1 ];then echo "$1 exists" else return 5 fi } fun $2 $1 [root@shell day5]# sh fun.sh /etc/hosts /etc/passwd /etc/passwd exists
思考:
#!/bin/sh fun(){ num=10 for i in `seq 10` do total=$[$i+$num] done echo "total的結果是: $total" } fun
傳參
#!/bin/sh #第一種定義方式 fun(){ num=$1 for i in `seq 10` do total=$[$i+$num] done echo "total的結果是: $total" } fun $2 $1 [root@shell day5]# sh fun.sh 20 30 total的結果是: 40
函數的變量
local num=20 只針對當前的函數生效 其他函數和語句無法接收local的變量
函數的返回值
#!/bin/sh fun(){ echo 100 return 1 } result=`fun` echo "函數的狀態碼是: $?" echo "函數的執行結果是: $result" 注意: $?上一條執行的如果有函數名稱 則返回函數內的return值 如果不相關則上一條命令的返回值
#!/bin/sh fun(){ if [ -f $1 ];then return 50 else return 100 fi } fun $1 #根據函數的返回狀態碼進行輸出結果 re=$? #[ $re -eq 50 ] && echo "文件存在" #[ $re -eq 100 ] && echo "文件不存在" if [ $re -eq 50 ];then echo "文件存在" elif [ $re -eq 100 ];then echo "文件不存在" fi
案例: 文件統計行
line 內置變量 按行讀取
[root@shell day5]# wc -l /etc/passwd 37 /etc/passwd [root@shell day5]# cat /etc/passwd|wc -l 37 [root@shell day5]# cat while1.sh #!/bin/h while read line do let i++ done</etc/passwd echo $i awk '{print NR}' /etc/passwd sed '=' /etc/passwd|xargs -n2 grep -n . /etc/passwd less -N /etc/passwd cat -n /etc/passwd