標籤:
6.shell函數
6.1.定義函數
簡介:
shell允許將一組命令集或語句形成一個可用塊,這些塊成為shell函數
定義函數的格式
方法一
函數名()
{
命令1
......
}
方法二
function 函數名()
{
命令1
......
}
函數定義的兩種方式
函數可以放在同一個檔案中作為一段代碼,也可以放在只包含函數的單獨檔案中
例子,在一個單獨檔案中只定義以下函數:
#!/bin/bash#hellofunfunction hello(){ echo "Hello, today is `date`" #`date` date用反引號括起來,表示在這條語句中先執行date命令,並將date命令的結果作為替換date位置的字串 return 1}
6.2.函數調用
例子
#!/bin/bash#funcfunction hello(){ echo "Hello,today is `date`"}echo "now going to the fuction hello"#接下來就是調用函數hellohelloecho "back from the function hello"
6.3.參數傳遞
簡介
向函數傳遞參數就像在指令碼中使用位置變數 $1、$2、...$9
例子
#!/bin/bash#funcfunction hello(){ echo "Hello, $1 today is `date`"}echo "now going to the fuction hello"#接下來就是調用函數hello,傳入參數 chinahello chinaecho "back from the function hello"
6.4.函數檔案
簡介:
可以將函數定義和函數調用放在同一個檔案中,也可以在一個檔案中專門定義函數,在其他檔案來調用該函數
例子:
在檔案 hellofun 中定義函數
#!/bin/bashfunction hello(){ echo "Hello, today is `date`" return 1}
在另一個檔案 func 中調用該函數
#!/bin/bash#載入檔案,標明定義函數的檔案,格式為:.空格檔案名稱(特別注意一定要在.和檔案名稱之間有空格). hellofunecho "now going to the fuction hello"helloecho "back from the function hello"
建議:
學習shell指令碼的時候,可以多看看linux系統的開機檔案來學習,但是注意在看的過程中,如果想要對它進行修改,一定要首先備份一下這個檔案,在對其進行修改,以便能在出錯時使用備份檔案挽回
6.5.載入和刪除函數
檢查載入函數和刪除函數
查看載入函數
set命令查看這個函數如何載入
例子:
#!/bin/bash. hellofunsetecho "now going to the fuction hello"helloecho "back from the function hello"
刪除函數
unset命令
例子
#!/bin/bash. hellofunset#使用unset使得接下來執行hello時候不能執行成功,因為unset刪除了函數unset helloecho "now going to the fuction hello"hello#這裡會輸出資訊:./func:hello:command not foundecho "back from the function hello"
6.6.函數返回狀態值
例子1:
#!/bin/bashfunction hello(){ echo "Hello, today is `date`" return 0}echo "now going to the function hello"hello#接下來來輸出返回狀態值,用 $? 表示echo $?echo "back from the function hello"
例子2:
#!/bin/bashfunction hello(){ echo "Hello, today is `date`" return 0}echo "now going to the function hello"returnvalue=hello#接下來來輸出返回狀態值,用 $? 表示echo $?echo $returnvalueecho "back from the function hello"#注意:不同於C語言等語言,shell指令碼中不能將函數的傳回值賦給變數#returnvalue=hello 不是將hello函數的傳回值賦給returnvalue,而是將hello字串賦給returnvalue
Shell編程基礎教程6--shell函數