将参数传递给 Bash 函数 [英] Passing parameters to a Bash function
问题描述
我正在尝试搜索如何在 Bash 函数中传递参数,但出现的总是如何从命令行传递参数.
I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.
我想在我的脚本中传递参数.我试过了:
I would like to pass parameters within my script. I tried:
myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
但是语法不正确.如何将参数传递给我的函数?
But the syntax is not correct. How can I pass a parameter to my function?
推荐答案
有两种典型的函数声明方式.我更喜欢第二种方法.
There are two typical ways of declaring a function. I prefer the second approach.
function function_name {
command...
}
或
function_name () {
command...
}
调用带参数的函数:
function_name "$arg1" "$arg2"
该函数通过它们的位置(而不是名称)来引用传递的参数,即 $1
、$2
等等.$0
是脚本本身的名称.
The function refers to passed arguments by their position (not by name), that is $1
, $2
, and so forth. $0
is the name of the script itself.
示例:
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.
输出:
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
这篇关于将参数传递给 Bash 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!