There are two typical ways of declaring a function.
(声明函数有两种典型方法。)
I prefer the second approach. (我更喜欢第二种方法。)
function function_name {
command...
}
or
(要么)
function_name () {
command...
}
To call a function with arguments:
(要使用参数调用函数:)
function_name "$arg1" "$arg2"
The function refers to passed arguments by their position (not by name), that is $1, $2, and so forth.
(该函数引用通过其位置(而不是名称)传递的参数,即$ 1,$ 2等等。)
$0 is the name of the script itself. ($ 0是脚本本身的名称。)
Example:
(例:)
function_name () {
echo "Parameter #1 is $1"
}
Also, you need to call your function after it is declared.
(此外,您需要在声明后调用您的函数。)
#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
Output:
(输出:)
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
Reference: Advanced Bash-Scripting Guide .
(参考:Advanced Bash-Scripting Guide 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…