文字列項目を介して新しい行を繰り返します。

文字列項目を介して新しい行を繰り返します。

これを実行すると:

abc="one
two
three"
for item in "$abc"; do echo "Item: $item"; done

私は得る:

item: one
two
three

しかし、私が期待するものは次のとおりです。

Item: one
Item: two
Item: three

私は何が間違っていましたか?

ベストアンサー1

変数を参照として渡します。つまり、単一の引数として扱われます。引用符を入れないでおくと、期待した結果が得られます(注これは他のさまざまな問題を引き起こす可能性があります。):

$ for item in $abc; do echo "Item: $item"; done
Item: one
Item: two
Item: three

しかし、必要なのは値のリストだけですが、なぜ文字列を使用するのですか?これが配列の目的です(bashを使用すると仮定)。

$ abc=(one two three)
$ for item in "${abc[@]}"; do echo "Item: $item"; done
Item: one
Item: two
Item: three

または、配列を理解するシェルを使用していない場合は、次のようにします。

$ abc="one           
two
three"
$ printf '%s\n' "$abc" | while read -r item; do echo "Item: $item"; done
Item: one
Item: two
Item: three

おすすめ記事