18

i'm trying to print a multi line strings in printf this way

printf "hi\n"
printf "next line here\n"

I can't do the following

text_content="
hi
next line here
"

printf $text_content

Is there any other way?

wolfgang
  • 7,281
  • 12
  • 44
  • 72
  • 1
    in what way does `printf "$text_content"` *not* work? It replicates the native new-lines in the assignment, as well as converting the `\n` to newlines for me as well. If you don't quote it, then word splitting would cause only the first word to be displayed – Anya Shenanigans Sep 03 '15 at 09:21
  • 1
    Why do you have both `\n` and embedded newlines in `text_content`? – chepner Sep 03 '15 at 11:10
  • @chepner my mistake, edited – wolfgang Sep 03 '15 at 12:13

3 Answers3

15

Quoting the variable should do the trick. In your example, however, you are getting double newlines.

printf "$text_content"
Reuben L.
  • 2,806
  • 2
  • 29
  • 45
  • 5
    If the variable has any `%` symbols it may be better to use `printf "%s\n" "$variable"` – user000001 Sep 03 '15 at 09:26
  • 1
    You really should always use a format string as the first argument, and quote all variables. `printf '%s\n' "$text_content"` (perhaps without the `\n` if the variable already contains all the newlines you want). See also [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Sep 08 '19 at 07:06
13

Here's another variation.

printf '%s\n' 'first line here' 'second line here'

You can add an arbitrary number of arguments; printf will repeat the format string until all arguments are exhausted.

printf '%s\n' '#!/bin/sh' \
    'for x; do' \
    '    echo "Welcome to my script!"' \
    'done' >script.sh
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 3
    I like this solution a lot. It makes use of bash line-continuation, a single printf format which does not need to be repeated, and avoids the [echo portability problems](https://www.in-ulm.de/~mascheck/various/echo+printf/) – kvantour Nov 13 '19 at 13:40
  • @SunggukLim If you have a specific situation where it is not working for you, you should probably ask a new question with a specific example. Please review the [help] and in particular [How to ask](/help/how-to-ask) as well as the guidance for providing a [mre]. – tripleee Mar 16 '23 at 06:11
1

If printf is not necessary, then you may use echo:

var="one\ntwo"
echo -e $var
Andrew
  • 958
  • 13
  • 25