「$@」の単一要素を出力するには?

「$@」の単一要素を出力するには?

$@私はこれが位置パラメータを保持する配列であることを読みました。

$@配列の要素を出力しようとしています。

echo ${@[1]}

しかし、bash私には次のエラーが発生しました。

test.sh: line 1: ${@[1]}: bad substitution

ベストアンサー1

$@「特殊パラメータ」は配列ではないため、配列としてアクセスできません。その場所を使用してパラメータに直接アクセスできます。${1}... 。${n}

$ set -- a b c d e f g h i j k l m n
$ echo "$#"
14
$ echo "${10}"
j

パラメータ10+の中かっこ動作が気になったので、さまざまなシェルでテストしました。

for shell in ash bash dash fish ksh mksh posh rc sash yash zsh
do
  printf "The %s shell outputs: %s\n" "$shell" "$($shell -c 'set -- a b c d e f g h i j k l m n; echo $10')"
done

次の結果は次のとおりです。

The ash shell outputs: j
The bash shell outputs: a0
The dash shell outputs: j
The fish shell outputs:
The ksh shell outputs: a0
The mksh shell outputs: a0
The posh shell outputs: a0
rc: cannot find `set'
The rc shell outputs:
The sash shell outputs: j
The yash shell outputs: a0
The zsh shell outputs: j

シェルパラメータの中括弧の動作は次のとおりです。シェルコマンド言語シェルパラメータ拡張部分:

パラメータ名または記号は中括弧で囲むことができます。これは、2 桁以上の位置引数を除くオプションです。

特殊パラメータ自体は$@同じページに記載されています。特殊パラメータ部分。

おすすめ記事