我如何在Bash中输出一个多重字符串,而不使用多个echo调用,像这样:
echo "usage: up [--level <n>| -n <levels>][--help][--version]"
echo
echo "Report bugs to: "
echo "up home page: "
我正在寻找一种可移植的方法来做到这一点,只使用Bash内置程序。
我如何在Bash中输出一个多重字符串,而不使用多个echo调用,像这样:
echo "usage: up [--level <n>| -n <levels>][--help][--version]"
echo
echo "Report bugs to: "
echo "up home page: "
我正在寻找一种可移植的方法来做到这一点,只使用Bash内置程序。
当前回答
同样,对于缩进的源代码,您可以使用<<-(带末尾破折号)来忽略前面的制表符(但不能忽略前面的空格)。
比如这个:
if [ some test ]; then
cat <<- xx
line1
line2
xx
fi
输出不带前导空格的缩进文本:
line1
line2
其他回答
You can write your
text
freely,
in a separate:
----file.
然后
echo "$(</pathto/your_multiline_file)"
这样做:
dedent() {
local -n reference="$1"
reference="$(echo "$reference" | sed 's/^[[:space:]]*//')"
}
text="this is line one
this is line two
this is line three\n"
# `text` is passed by reference and gets dedented
dedent text
printf "$text"
不先调用dedent的输出:
this is line one
this is line two
this is line three
...和WITH首先调用dedent(如上所示):
this is line one
this is line two
this is line three
完整的解释,请看我已经写过的地方:
相当于python在bash中的textwrap dedent 带额外空格的多行字符串(保留缩进)
当然,感谢@Andreas Louv在这里向我展示了该函数的sed部分。
我通常使用内置的read命令,我认为它更灵活和直观。 它将一行内容读入一个变量,并允许与特殊shell变量IFS绑定的分词。 更多细节请参考本博客或手册页。
read -r -d '' usage <<-EOF
usage: up [--level <n>| -n <levels>][--help][--version]
Report bugs to: $report server
up home page: $HOME
EOF
echo "$usage"
使用-e选项,则可以在字符串中打印带\n的新行字符。
例如:
echo -e "This will be the first line \nand this will be on the second line"
或者你可以这样做:
echo "usage: up [--level <n>| -n <levels>][--help][--version]
Report bugs to:
up home page: "