shell腳本函數(shù)及傳參 | 您所在的位置:網(wǎng)站首頁 › 屬羊人守護神是哪位菩薩 › shell腳本函數(shù)及傳參 |
shell函數(shù)的定義
shell腳本的函數(shù)位置相對自由,既可以一個shell腳本單獨成一個函數(shù), 也可以在主代碼中嵌入內(nèi)置函數(shù). 在Shell中可以通過下面的兩種語法來定義函數(shù),分別如下: function_name () { statement1 statement2 .... statementn }或者 function function_name() { statement1 statement2 .... statementn } shell腳本函數(shù)傳參當某個函數(shù)定義好了以后,用戶就可以通過函數(shù)名來調(diào)用該函數(shù)了。在Shell中,函數(shù)調(diào)用的基本語法如下, function_name parm1 parm21 例如下面的腳本: #!/usr/bin/env bash # encoding: utf-8.0 function test_func() { echo "output from inside-function:test_func" echo 'input parameter1: '$1 echo 'input parameter2: '$2 } echo "here is main function" echo "now inside function: test_func" test_func hello world運行后輸出: here is main function now inside function: test_func input parameter1: hello input parameter2: world還可以更復雜一些.例如整個shell腳本還有控制臺的輸入?yún)?shù): #!/usr/bin/env bash # encoding: utf-8.0 function test_func() { echo "output from inside-function:test_func" echo 'input parameter1: '$1 echo 'input parameter2: '$2 } function print_list() { while read LINE do echo $LINE done < $1 } echo "here is main function" echo "now inside function: test_func" test_func hello world print_list $1運行./shell_function.test list.txt得到的輸出如下.可見內(nèi)置函數(shù)內(nèi)的參數(shù)列表和腳本的參數(shù)列表互相并不影響. here is main function now inside function: test_func output from inside-function:test_func input parameter1: hello input parameter2: world line1 line2 line3 line4 |
今日新聞 |
推薦新聞 |
專題文章 |
CopyRight 2018-2019 實驗室設備網(wǎng) 版權所有 |