shell指令碼函式及傳參
阿新 • • 發佈:2019-01-25
shell函式的定義
shell指令碼的函式位置相對自由,既可以一個shell指令碼單獨成一個函式, 也可以在主程式碼中嵌入內建函式.
在Shell中可以通過下面的兩種語法來定義函式,分別如下:
function_name ()
{
statement1
statement2
....
statementn
}
或者
function function_name()
{
statement1
statement2
....
statementn
}
shell指令碼函式傳參
當某個函式定義好了以後,使用者就可以通過函式名來呼叫該函數了。在Shell中,函式呼叫的基本語法如下,
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指令碼還有控制檯的輸入引數:
#!/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
得到的輸出如下.可見內建函式內的引數列表和指令碼的引數列表互相併不影響.
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