shell指令碼中函式的呼叫
阿新 • • 發佈:2018-12-30
函式 : 把一個功能封裝起來,使用時直接呼叫函式名,這樣的指令碼好處:模組化,程式碼可讀性強,擴充套件性方便函式的定義 在shell 中有兩種定義函式的語法格式,分別為: 函式名() { 命令序列 } 或者: function 函式名() /function 可以不寫 { 命令序列 }函式的呼叫在函式定義好後,使用者可以在shell 中直接呼叫,呼叫時不用帶上() 例1. 定義example函式,並呼叫函式[[email protected] ~]# vim case1.sh 1 #!/bin/bash 2 abc=123 3 #define function 4 example() 5 { 6 abc=456 7 } 8 echo $abc 9 #呼叫函式10 example11 echo $abc 例2 . 定義delete函式,呼叫函式[[email protected] ~]# vim case3.sh 1 #!/bin/bash 2 delete() 3 { 4 rm -rf $1 5 mkdir $2 6 } 7 8 delete ~/a.txt ~/mydir例3 . 通過指令碼呼叫其他模組中的函式,編寫一個 檔案備份db-backup指令碼通常,呼叫函式是通過source 命令來呼叫其他指令碼中的函式首先,定義一個包含不同函式的功能模組
然後, 編寫shell,呼叫函式
- 呼叫語法
- 函式中的變數
- 函式的呼叫
[[email protected] ~]# vim moudle.sh 1 #!/bin/bash 2 delete() 3 { 4 rm -rf $de 5 } 6 copy() 7 { 8 cp -rf $sdir $tdir 9 } 10 backup() 11 { 12 tar zcvf $tar_name $tar_dir &> /dev/null 13 } 14 quit() 15 { 16 exit 17 } 18
然後, 編寫shell,呼叫函式
[[email protected] ~]# vim db-backup.sh
1 #!/bin/bash
2 source /root/moudle.sh /呼叫 moudle.sh 指令碼中的函式
3 while true
4 do
5 cat <<EOF
6 *******************************
7 The following is optional
8 *******************************
9 1) Copy
10 2) Delete
11 3) Backup
12 4) Exit
13 *******************************
14 EOF
15 read -p "please enter your chioce:" option
16 case $option in
17 1)
18 read -p "Please input the file you want to copy:" sdir19 read -p "Please input the directory you want to copy:" tdir20 copy
21 ;;
22 2)
23 read -p "Please input your target file:" de24 delete
25 ;;
26 3)
27 read -p "Please input the backupfile name:" tar_name28 read -p "Please input the file you want to backup:" tar_dir29 backup /注意上面這些變數都要和引用函式指令碼的變數一致。30 ;;
31 4)
32 quit;break
33 ;;
34 *)
35 echo "option is inviald."
36 esac