コマンドのパラメータをスクリプトに転送するために2つの変数($ @、$ *)を使用する目的は何ですか? [コピー]

コマンドのパラメータをスクリプトに転送するために2つの変数($ @、$ *)を使用する目的は何ですか? [コピー]

で使用されているスクリプト$@と特殊変数を読みました$*。私が理解したところ、スクリプトを実行するときに使用されるパラメータは、$@すべてのパラメータが存在する場合は$*スクリプト内でアクセスできるように2つの特殊変数に格納されます。

同じパラメータセットに2つの特殊変数が必要な理由を理解できません。 1つの特殊変数を使用する場合と別の特殊変数を使用する場合の違いは何ですか?

ここに画像の説明を入力してください。

ベストアンサー1

簡単で独創的な説明は次のとおりです。

  • $*設定されたすべてのパラメータは文字列です(パラメータは最初の文字で区切られています$IFS)。
  • $@各パラメータは異なる文字列です(改行文字で区切られたパラメータ)。

からman bash

* Expands to the positional parameters, starting from one.  When the expansion is not within  dou‐
  ble  quotes, each positional parameter expands to a separate word.  In contexts where it is per‐
  formed, those words are subject to further word splitting  and  pathname  expansion.   When  the
  expansion occurs within double quotes, it expands to a single word with the value of each param‐
  eter separated by the first character of the IFS special variable.  That is, "$*" is  equivalent
  to  "$1c$2c...",  where  c  is  the first character of the value of the IFS variable.  If IFS is
  unset, the parameters are separated by spaces.  If IFS is null, the parameters are joined  with‐
  out intervening separators.
@ Expands  to the positional parameters, starting from one.  When the expansion occurs within dou‐
  ble quotes, each parameter expands to a separate word.  That is, "$@" is equivalent to "$1" "$2"
  ...   If  the double-quoted expansion occurs within a word, the expansion of the first parameter
  is joined with the beginning part of the original word, and the expansion of the last  parameter
  is  joined  with  the  last part of the original word.  When there are no positional parameters,
  "$@" and $@ expand to nothing (i.e., they are removed).

おすすめ記事