How to break a long string into multiple lines in the prompt of read -p within the source code?
First of all, let's decouple the read from the text line by using a variable:
text="line-1 line-2" ### Just an example.
read -p "$text" REPLY
In this way the problem becomes: How to assign two lines to a variable.
Of course, a first attempt to do that, is:
a="line-1 \
line-2"
Written as that, the var a
actually gets the value line-1 line-2
.
But you do not like the lack of indentation that this creates, well, then we may try to read the lines into the var from a here-doc (be aware that the indented lines inside the here-doc need a tab, not spaces, to work correctly):
a="$(cat <<-_set_a_variable_
line-1
line-2
_set_a_variable_
)"
echo "test1 <$a>"
But that would fail as actually two lines are written to $a
.
A workaround to get only one line might be:
a="$( echo $(cat <<-_set_a_variable_
line 1
line 2
_set_a_variable_
) )"
echo "test2 <$a>"
That is close, but creates other additional issues.
Correct solution.
All the attempts above will just make this problem more complex that it needs to be.
A very basic and simple approach is:
a="line-1"
a="$a line-2"
read -p "$a" REPLY
The code for your specific example is (for any shell whose read
supports -p
):
#!/bin/dash
a="goat can try change directory if cd fails to do so."
a="$a Would you like to add this feature? [Y|n] "
# absolute freedom to indent as you see fit.
read -p "$a" REPLY
For all the other shells, use:
#!/bin/dash
a="goat can try change directory if cd fails to do so."
a="$a Would you like to add this feature? [Y|n] "
# absolute freedom to indent as you see fit.
printf '%s' "$a"; read REPLY