0

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.
James T.
  • 910
  • 1
  • 11
  • 24

2 Answers2

2

$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"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

Looking through for string splitting options, I found I could do this

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

IFS=$'\n'

printf '%s\n' $help

unset IFS

you can also do a for line in $help; do echo $line done instead of the using the printf command.

src: https://unix.stackexchange.com/questions/184863/what-is-the-meaning-of-ifs-n-in-bash-scripting

src2: How can I have a newline in a string in sh?

James T.
  • 910
  • 1
  • 11
  • 24