Bashの関数にパラメータを渡す

Bashの関数でパラメータを渡す方法を検索しようとしているのですが、出てくるのはいつもコマンドラインからパラメータを渡す方法です。

私はスクリプト内でパラメータを渡したいのです。私は試してみました。

myBackupFunction("..", "...", "xx")

function myBackupFunction($directory, $options, $rootPassword) {
     ...
}

しかし、構文が正しくありません。関数にパラメータを渡すにはどうしたらよいでしょうか?

ソリューション

関数を宣言する代表的な方法は2つあります。私は2番目の方法が好きです。

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

参考:Advanced Bash-Scripting Guideを参照してください。

解説 (9)

高レベルのプログラミング言語(C/C++/Java/PHP/Python/Perl ...)の知識があれば、bashの関数はそれらの言語と同じように動作するはずだと素人には思えるでしょう。代わりに、bash関数はシェルコマンドのように動作し、シェルコマンド(ls -l)にオプションを渡すのと同じように、引数が渡されることを期待します。事実上、bashの関数の引数位置パラメーターとして扱われます($1, $2...$9, ${10}, ${11}など)。これは、getoptsの仕組みを考えれば当然のことです。bashでは、関数を呼び出すのに括弧は必要ありません。


(: 私はたまたま現在Open 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
解説 (0)

括弧やカンマを外します。

 myBackupFunction ".." "..." "xx"

とすると、関数は次のようになります。

function myBackupFunction() {
   # here $1 is the first parameter, $2 the second etc.
}
解説 (0)