我如何在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内置程序。
当前回答
使用-e选项,则可以在字符串中打印带\n的新行字符。
例如:
echo -e "This will be the first line \nand this will be on the second line"
其他回答
使用-e选项,则可以在字符串中打印带\n的新行字符。
例如:
echo -e "This will be the first line \nand this will be on the second line"
受到本页上富有洞察力的回答的启发,我创造了一个混合的方法,我认为这是最简单和更灵活的方法。你怎么看?
首先,我在一个变量中定义了它的用法,这允许我在不同的上下文中重用它。格式非常简单,几乎是所见即所得,不需要添加任何控制字符。对我来说,这似乎是合理的可移植性(我在MacOS和Ubuntu上运行它)
__usage="
Usage: $(basename $0) [OPTIONS]
Options:
-l, --level <n> Something something something level
-n, --nnnnn <levels> Something something something n
-h, --help Something something something help
-v, --version Something something something version
"
那么我就可以简单地把它用作
echo "$__usage"
或者更好的是,当解析参数时,我可以在一行中回显它:
levelN=${2:?"--level: n is required!""${__usage}"}
You can write your
text
freely,
in a separate:
----file.
然后
echo "$(</pathto/your_multiline_file)"
或者你可以这样做:
echo "usage: up [--level <n>| -n <levels>][--help][--version]
Report bugs to:
up home page: "
在这里,文档通常用于此目的。
cat << EOF
usage: up [--level <n>| -n <levels>][--help][--version]
Report bugs to:
up home page:
EOF
所有boure派生的shell(包括所有版本的Bash)都支持它们。