Reputation: 978
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.
Upvotes: 0
Views: 40
Reputation: 361585
$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"
Upvotes: 2
Reputation: 978
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?
Upvotes: 0