如何在Bash中输出多行字符串?

424

如何在Bash中输出多行字符串而不使用多个echo调用,类似于以下方式:

echo "usage: up [--level <n>| -n <levels>][--help][--version]"
echo 
echo "Report bugs to: "
echo "up home page: "

我正在寻找一种便携的方式,只使用Bash内置工具实现。


6
如果您在回应错误的调用时输出使用消息,通常应该将该消息发送到标准错误流而不是标准输出流,可以使用echo >&2 ... - Mark Reed
3
使用信息可以通过输入 --help 命令输出(应该输出到标准输出)。 - helpermethod
3
对于其他人,有关“here documents”的更多信息可在以下网址找到:http://www.tldp.org/LDP/abs/html/here-docs.html - Jeffrey Martinez
1
请查看Gordon Davidson的基于printf的解决方案。尽管在echocat的基础上处于阴影之中,但它似乎要少得多。不可否认,printf语法代表了一定的学习曲线,但我想听听其他缺点(兼容性、性能等...)。 - mjv
1
相关:https://dev59.com/MWAg5IYBdhLWcg3wI4LD - Anton Tarasenko
12个回答

1
基于@Gabriel Staples的回答进行扩展...
创建这两个函数。
dedent() {
    local -n reference="$1"
    reference="$(echo "$reference" | sed 's/^[[:space:]]*//')"
}

log_multi() {
    dedent $1
    printf "$1"
}

# then log
log_multi "
from os import path
import os
def test_dummy():
    assert 1==1
"


-1

这是我做的方式:

function help_text {
  printf "\n\
Usage: ./cpanel-to-cc.sh [arguments] ... \n\
Examples: \n\
\t ./cpanel-to-cc.sh --client-id 123123 --api-key abc123def456 --domain example.com \n\
\t ./cpanel-to-cc.sh --client-id 123123 --tmp-dir /home/user/cpanel-to-cc \n\
\t ./cpanel-to-cc.sh --resync --domain example.com \n\
\t ./cpanel-to-cc.sh --purge \n\
\n\
Arguments: \n\
Option \t\t\t Long option \t\t\t Function \n\
 -c <id> \t\t --client-id <id> \t\t Specify the SiteHost Client ID \n\
 -k <key> \t\t --api-key <key> \t\t Specify the SiteHost API key with access to Cloud, Job and Server modules \n\
 -d <domain> \t\t --domain <domain> \t\t The cPanel domain to migrate. If not specified we try migrate all \n\
 -t <directory> \t --tmp-dir <directory> \t\t Directory to store temporary files and logs. Default is: $TMP_DIR \n\
 -v \t\t\t --verbose \t\t\t Print debugging/verbose information \n\
 -y \t\t\t --assume-yes \t\t\t Automatic yes to prompts. Assume \"yes\" as answer to all prompts \n\
 -r \t\t\t --resync \t\t\t Use credentials stored and copy data into Container already created. \n\
 -p \t\t\t --purge \t\t\t Remove any metadata stored on the the server. This removes any files in: $TMP_DIR \n\
 -h \t\t\t --help \t\t\t Display this help and exit \n\
 \n"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接