将参数传递给Bash函数
我正在尝试搜索如何在Bash函数中传递参数,但是总会出现如何从命令行传递参数的问题。
我想在我的脚本中传递参数。 我试过了:
myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
     ...
}
但语法不正确,如何将参数传递给我的函数?
有两种声明函数的典型方法。 我更喜欢第二种方法。
function function_name {
   command...
} 
要么
function_name () {
   command...
} 
用参数调用一个函数:
function_name "$arg1" "$arg2"
该函数通过它们的位置(而不是名称)引用传递的参数,即$ 1,$ 2等等。 $ 0是脚本本身的名称。
例:
function_name () {
   echo "Parameter #1 is $1"
}
另外,你需要在声明后调用你的函数。
#!/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脚本指南。
  对高级编程语言(C / C ++ / Java / PHP / Python / Perl ...)的了解会让外行知道bash函数应该像其他语言一样工作。  相反,bash函数的工作方式与shell命令相似,并希望将参数传递给它们,方法与传递shell命令(ls -l)的选项相同。  实际上,bash中的函数参数被视为位置参数( $1, $2..$9, ${10}, ${11}等)。  考虑到getopts工作原理,这并不奇怪。  圆括号不需要在bash中调用函数。 
( 注意 :目前我正在开发Solaris。)
# bash style declaration for all you PHP/JavaScript junkies. :-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
function backupWebRoot () {
    tar -cvf - $1 | zip -n .jpg:.gif:.png $2 - 2>> $errorlog &&
        echo -e "nTarball created!n"
}
# sh style declaration for the purist in you. ;-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
backupWebRoot () {
    tar -cvf - $1 | zip -n .jpg:.gif:.png $2 - 2>> $errorlog &&
        echo -e "nTarball created!n"
}
#In the actual shell script
#$0               $1            $2
backupWebRoot ~/public/www/ webSite.tar.zip
错过了父母和逗号:
 myBackupFunction ".." "..." "xx"
该函数应该看起来像这样:
function myBackupFunction() {
   # here $1 is the first parameter, $2 the second etc.
}
上一篇: Passing parameters to a Bash function
下一篇: Pass input and output files desired PATH to a binary in bash
