シェルが関数のパラメーターを必要としないのはなぜですか? num1 と num2 を加算する以下の加算関数の例。行関数のaddition()の()内にパラメータを記述しないということです。
addition()
{
echo $(($num1+$num2))
}
なぜこの関数が機能するのか、num1 変数と num2 変数を取得する方法について質問がある場合、答えは次のとおりです:親コンテキストからこれらの変数を取得します。たとえば、次のように表示されますhello Jack
。
hello() {
echo hello $name
}
name=Jack
hello
次のように位置引数を使用するように関数を書き直すことができます。
hello() {
echo hello $1
}
hello Jack
関数宣言に変数名を書かない理由に従って、それbash
が作られる方法です。マニュアルページから:
Shell Function Definitions
A shell function is an object that is called like a simple command and
executes a compound command with a new set of positional parameters.
Shell functions are declared as follows:
name () compound-command [redirection]
function name [()] compound-command [redirection]
This defines a function named name. The reserved word function
is optional. If the function reserved word is supplied, the
parentheses are optional. The body of the function is the com‐
pound command compound-command (see Compound Commands above).
....
つまり、関数宣言は、説明された形式のいずれかである必要があり、キーワード()
を使用しない場合は必須であり、それ以外の場合はオプションです (その間に変数名はありません) 。function
シェル関数はプロトタイプを必要としません。
$#
ため、関数本体は可変個引数関数を処理できます。マンページから:
関数が実行されると、関数への引数は、その実行中に定位置パラメーターになります。特別なパラメーター # が更新され、変更が反映されます。特殊パラメータ 0 は変更されません。
CS 用語では、bash 関数は正式なパラメーターを使用しません。これは、関数を適用するとき (およびそのときのみ) に位置パラメーターが常に設定されるためです。
$ ##
$ # Show the function arguments
$ showParams() {
> printf '%s\n' "$@"
$ }
$ showParams 1 2 3
1
2
3
$ set -- 1 2 3
$ printf '%s\n' "$@"
1
2
3
$ showParams # Here you can see the parameters in the shell are not set in the function application:
$
…しかしこれは、bash がキーワード引数をサポートしていないことも意味します。
また、マンページの位置パラメーターの下のセクションもお読みください。