416

How can I output a multipline string in Bash without using multiple echo calls like so:

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

I'm looking for a portable way to do this, using only Bash builtins.

helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • 6
    If you're outputting a usage message in response to an incorrect invocation, you would normally send that message to standard error instead of standard output, with `echo >&2 ...` – Mark Reed Jun 10 '12 at 17:05
  • 3
    @MarkReed The usage message is output by typing `--help` (which should go to standard out). – helpermethod Jun 12 '12 at 10:00
  • 3
    For others who come along, more info about "here documents" is available: http://www.tldp.org/LDP/abs/html/here-docs.html – Jeffrey Martinez Dec 31 '15 at 08:08
  • 1
    Check the `printf`-based solution from Gordon Davidson. Despite being in the shadow of the `echo` or `cat` based approaches, it seems to be much less of a kludge. Admittedly the `printf' syntax represent a bit of a learning curve, but I'd like to ear of other drawbacks (? compatibility, performance ? ...) – mjv Apr 26 '17 at 23:49
  • 1
    Related: https://stackoverflow.com/questions/23929235/multi-line-string-with-extra-space-preserved-indentation – Anton Tarasenko Oct 22 '17 at 10:03

12 Answers12

477

Here documents are often used for this purpose.

cat << EOF
usage: up [--level <n>| -n <levels>][--help][--version]

Report bugs to: 
up home page:
EOF

They are supported in all Bourne-derived shells including all versions of Bash.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
270

or you can do this:

echo "usage: up [--level <n>| -n <levels>][--help][--version]

Report bugs to: 
up home page: "
Chris Mohr
  • 3,639
  • 1
  • 13
  • 9
  • 2
    @OliverWeiler: It will even work in Bourne shells such as Dash and the [Heirloom Bourne Shell](http://heirloom.sourceforge.net/sh.html). – Dennis Williamson Jun 10 '12 at 17:05
  • 17
    Not great if you need this in a function because you'll either need to 1) outdent the string all the way to the left of your file or 2) keep it indented to line up with the rest of your code but then it prints with the indents as well – s g Oct 19 '18 at 20:45
  • 4
    Works. Also note use ' (single quotes) instead of " (double quotes) if you don't want the interpretation of the string. If you want $something or `something` in the output instead of it getting replaced. – Eric Nov 06 '21 at 15:03
103

Inspired by the insightful answers on this page, I created a mixed approach, which I consider the simplest and more flexible one. What do you think?

First, I define the usage in a variable, which allows me to reuse it in different contexts. The format is very simple, almost WYSIWYG, without the need to add any control characters. This seems reasonably portable to me (I ran it on MacOS and 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
"

Then I can simply use it as

echo "$__usage"

or even better, when parsing parameters, I can just echo it there in a one-liner:

levelN=${2:?"--level: n is required!""${__usage}"}
Jorge
  • 1,317
  • 1
  • 11
  • 6
  • 4
    this worked for me in a script where the above answer does not (without modification). – David Welch Sep 25 '18 at 00:16
  • 6
    This is much cleaner than involving a bunch of characters like \t and \n which are hard to find in the text and expand to make the output much different than the string in the script – s g Oct 19 '18 at 20:53
  • 2
    For some reasons it prints everything on the same line for me :/ – Nicolas de Fontenay Mar 13 '20 at 15:36
  • 6
    @Nicolas: Using double quotes in `echo "$__usage"` was necessary for me. `echo $__usage` did not work. – Mario Apr 10 '20 at 10:15
  • 2
    If you use the solution from @jorge and find that everything is on the same line, make sure you enclose the variable in quotes: ``` echo $__usage ``` will print everything on one line whereas ``` echo "$__usage" ``` will retain the newlines. – user1165471 Apr 09 '20 at 17:12
  • 1
    This is actually the one solution that worked for me. Printf does a lot of things and with my multiline xml, it probably requires a lot of escaping because it completely mangles the content. I assign foo=`cat < – Jilles van Gurp May 23 '20 at 11:27
56

Use -e option, then you can print new line character with \n in the string.

For example:

echo -e "This will be the first line \nand this will be on the second line"
Dharman
  • 30,962
  • 25
  • 85
  • 135
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • 7
    Those man pages are for the system-supplied `echo` command, `/bin/echo`, which on Mac OS has no `-e` option. when you're using bash on those systems, its built-in `echo` command takes over. You can see this by explicitly typing `/bin/echo whatever` and observing the difference in behavior. To see the documentation for the built-in, type `help echo`. – Mark Reed Jun 10 '12 at 16:59
  • 1
    `/bin/echo` is often different from one OS to another and different from Bash's builtin `echo`. – Dennis Williamson Jun 10 '12 at 17:01
  • @MarkReed: I'll try later, but thanks for the info. +1. I will just leave my answer here, since there are quite a lot of good discussion going on. – nhahtdh Jun 10 '12 at 17:01
  • 9
    `echo -e` is not portable -- for example, some implementations of echo will print the "-e" as part of the output. If you want portability, use printf instead. For example, /bin/echo on OS X 10.7.4 does this. IIRC the bash builtin echo was also weird under 10.5.0, but I don't remember the details any more. – Gordon Davisson Jun 10 '12 at 17:02
  • 2
    `echo -e` has bitten me before... Definitely use `printf` or `cat` with a heredoc. The `<<-` variant of here docs are especially nice because you can strip leading indentation in the output, but indent for readability in the script – zbeekman Jun 07 '17 at 02:10
26

Since I recommended printf in a comment, I should probably give some examples of its usage (although for printing a usage message, I'd be more likely to use Dennis' or Chris' answers). printf is a bit more complex to use than echo. Its first argument is a format string, in which escapes (like \n) are always interpreted; it can also contain format directives starting with %, which control where and how any additional arguments are included in it. Here are two different approaches to using it for a usage message:

First, you could include the entire message in the format string:

printf "usage: up [--level <n>| -n <levels>][--help][--version]\n\nReport bugs to: \nup home page: \n"

Note that unlike echo, you must include the final newline explicitly. Also, if the message happens to contain any % characters, they would have to be written as %%. If you wanted to include the bugreport and homepage addresses, they can be added quite naturally:

printf "usage: up [--level <n>| -n <levels>][--help][--version]\n\nReport bugs to: %s\nup home page: %s\n" "$bugreport" "$homepage"

Second, you could just use the format string to make it print each additional argument on a separate line:

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

With this option, adding the bugreport and homepage addresses is fairly obvious:

printf "%s\n" "usage: up [--level <n>| -n <levels>][--help][--version]" "" "Report bugs to: $bugreport" "up home page: $homepage"
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
23

Also with indented source code you can use <<- (with a trailing dash) to ignore leading tabs (but not leading spaces).

For example this:

if [ some test ]; then
    cat <<- xx
        line1
        line2
xx
fi

Outputs indented text without the leading whitespace:

line1
line2
Elliptical view
  • 3,338
  • 1
  • 31
  • 28
  • That did not work for me. What shell are you using? – four43 Jun 11 '19 at 22:55
  • Did not work in bash 4.4.19 in Ubuntu. It did not remove the spacing before line1 and line2 – four43 Jun 12 '19 at 20:22
  • 1
    @four43, You were right. Does not work to remove leading spaces. However, does remove leading tabs. So I corrected my answer from tabs and spaces, to tabs and not spaces. Sorry for the mistake. I checked the manual and it clearly just says tabs are removed. Thanks for bringing this to my attention. – Elliptical view Jun 13 '19 at 23:03
  • It works with bash and zsh on MacOS 11.4. Great tip! – Philipp Jun 06 '21 at 22:03
  • ProTip: Use double quotes around your delimiter to escape things, like `"xx"`. – Joshua Pinter May 03 '22 at 21:16
20

I usually go with the builtin read command which I think is more flexible and intuitive. It reads the contents of a line into a variable, and allows for word splitting that is tied to the special shell variable IFS. Refer to this blog or even the man page for more details.

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"
Zstack
  • 4,046
  • 1
  • 19
  • 22
  • 2
    Best thing about this is that `<<-` (with the minus sign) ignores leading tab characters so that you can indent your message inside the code without indenting it when printed. – BUFU Oct 25 '21 at 08:24
6

One more thing, using printf with predefined variable (here: msg) as template.

msg="First line %s
Second line %s
Third line %s
"

one='additional message for the first line'
two='2'
tri='this is the last one'

printf "$msg" "$one" "$two" "$tri"

This ^^^ will print whole message with additional vars inserted instead of %s in provided order.

Ivan
  • 6,188
  • 1
  • 16
  • 23
1
    You can write your
    text
        freely,
                   in a separate: 
                             ----file.

and then

echo "$(</pathto/your_multiline_file)"
assayag.org
  • 709
  • 10
  • 24
1

Do this:

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"

Output withOUT calling dedent first:

this is line one
      this is line two
      this is line three

...and WITH calling dedent first (as shown above):

this is line one
this is line two
this is line three

For a full explanation, see where I've already written about this:

  1. Equivalent of python's textwrap dedent in bash
  2. Multi-line string with extra space (preserved indentation)

And of course, thanks to @Andreas Louv for showing me the sed part of that function here.

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
  • 1
    Note: Does not preserve indentation. See also https://stackoverflow.com/a/63228433/724752 – David Winiecki Apr 22 '22 at 20:32
  • @DavidWiniecki, yeah, I should fix this someday by writing a more-complicated and programmatic version of the `dedent` function. Then, I can make it a bash library, with unit tests and all, and import (source) it wherever needed, as I explain about bash libraries here: [Detailed example: how do you write, import, use, and test libraries in Bash?](https://stackoverflow.com/a/76241268/4561887). That would be cool. – Gabriel Staples Jun 07 '23 at 17:59
1

Building on @Gabriel Staples's answer...

Create these two functions.

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
"

Anthony M.
  • 98
  • 5
-1

Here is how I've done:

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"
}