bashmacosbash4

How do I add newline character at end of lines in blockquote for printing?


I'm using MacOS and Bash 4.4.23.

I want to be able to have a long blockquote in a single string for a help dialogue and print that in the program.

Suppose I have a string in var help

help='Searches a user to
see if he exists.'

help2='Searches a user to\n
see if he exists.'

echo $help # all one line
echo $help2 # all one line (with literal \n)

printf $help # prints 'Searches'
printf $help2 # same ^

I also tried

help3=$'Searches a user\n
to see if he exists.'

but I still don't get my expected results.

What I want to be printed:

Searches a user to
see if he exists.

Solution

  • $help is set correctly; what needs fixing is when it's expanded. As a rule of thumb you should almost always quote variables when they're expanded. Doing so here will preserve the embedded newline(s).

    help='Searches a user to
    see if he exists.'
    
    echo "$help"