换行符 ( ) 在 bash 的 END 块中不起作用[重复]

问题描述 投票:0回答:1

我需要在

\n
中定义“
END block
”,因为它将作为参数传递给其他 bash 脚本。

我在

empty newline
begin
处添加了
end
。但只有
begin empty line (\n)
起作用,而
end empty line (\n)
不起作用。

这是测试脚本:

string="$(cat <<"END"

foo
the "newline(\n)" in "END" before the foo is working
but "newline(\n)" in "END" after the bar is not working
bar

END
)"

echo ""
echo "--- method 1 - define \n in END block ---"
echo ""

printf "%s" "first line in single line (method 1)"
printf "%s" "$string"
printf "%s" "last line in single line (method 1)"

echo ""
echo ""
echo "--- method 2 - define \n in printf ---"
echo ""

printf "%s" "first line in single line (method 2)"
printf "%s\n" "$string"
printf "%s" "last line in single line (method 2)"

这是输出:

--- method 1 - define \n in END block ---

first line in single line (method 1)
foo
the "newline(\n)" in "END" before the foo is working
but "newline(\n)" in "END" after the bar is not working
barlast line in single line (method 1)

--- method 2 - define \n in printf ---

first line in single line (method 2)
foo
the "newline(\n)" in "END" before the foo is working
but "newline(\n)" in "END" after the bar is not working
bar
last line in single line (method 2)

这是预期的输出:

--- method 1 - define \n in END block ---

first line in single line (method 1)
foo
the "newline(\n)" in "END" before the foo is working
but "newline(\n)" in "END" after the bar is not working
bar
last line in single line (method 1)

如何设置

\n
中的“
END block
”以使其与
method 1
一起使用?

bash ubuntu printf cat
1个回答
0
投票

这太疯狂了。简单明了的语法是

string='
foo
the "newline(\n)" in "END" before the foo is working
but "newline(\n)" in "END" after the bar is not working
bar

'

您的尝试不起作用的主要原因是,根据定义,shell 会从命令替换中删除最后的换行符。

© www.soinside.com 2019 - 2024. All rights reserved.