ヒアドキュメントで定義された変数をコマンドに渡す方法

ヒアドキュメントで定義された変数をコマンドに渡す方法

このヒアドキュメント定義変数をコマンドに渡すにはどうすればいいでしょうか?

read -r -d '' tables <<'EOF'
table1
table2
table3
EOF

tables=$(tr '\n' ' ' < "$tables");

テーブル変数を次のように定義します。

table1 table2 table3

答え1

bashでは、ここに文字列

tables=$(tr '\n' ' ' <<< "$tables")

他のシェルでは、別のここに文書

tables=$(tr '\n' ' ' << END
$tables
END
)

答え2

通常は複数行の文字列を使用します。

tables="
table1
table2
table3"

echo $tables
for table in $tables; do echo $table; done

heredoc私のシステムでは あなたのは同等に扱われます

答え3

複数行の変数を取得したら、次のように使用できますecho

echo "$tables" | tr '\n' ' '

必ず二重引用符を使用してください守る改行。比較:

$ echo $tables | tr '\n' '_'
table1 table2 table3_

と:

$ echo "$tables" | tr '\n' '_'
table1_table2_table3_

関連情報