如何將heredoc定義的變數傳遞給命令

如何將heredoc定義的變數傳遞給命令

如何將這個heredoc定義的變數傳遞給指令?

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

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

我希望表變數定義為:

table1 table2 table3

答案1

對於 bash,您可以使用這裡的字串

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

對於其他 shell,您可以使用其他這裡的文檔

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_

相關內容