9

How could I break a line using \n in read -p?

For example

read -p "Please Enter the percent [30 between 100]\n The value is  Default = 80   :" scale_percent

I want \n to break a line but it doesn't work.

In echo I use -e and it breaks a line.

So I tried

read -ep 

to break the line but it didn't break the line. How can I do that?

And could you also please give me a good manual for read -p on the Internet because I couldn't find a nice one without a confusing description.

Nelson
  • 49,283
  • 8
  • 68
  • 81
Medya Gh
  • 4,563
  • 5
  • 23
  • 35

2 Answers2

10

You can do it this way:

read -p $'Please Enter the percent [30 between 100]\x0a The value is  Default = 80   :' scale_percent

we use above syntax to insert hex values, we insert \x0a which is the hexadecimal value of the newline character (LF). You can use same syntax above with echo to produce new lines, eg:

echo $'One line\x0asecond line'

This is a feature of BASH 2, it is documented here, the $'' is used to translate all escape sequences inside it for its ascii transcription. So we could obtain the same result of example above, this way:

echo $'One line\nsecond line'
Nelson
  • 49,283
  • 8
  • 68
  • 81
  • Awesome thank you, where do you learn these things ? is there any book or just experience ? – Medya Gh Oct 05 '12 at 09:39
  • I learned by experience, specifically http://stackoverflow.com/a/4745850/352672 Also there are docs, will update my answer with that. – Nelson Oct 05 '12 at 10:10
  • @MedyaGh: You can also find documentation when you run `man bash` and search for chapter heading `QUOTING`. – mklement0 Mar 26 '16 at 22:33
1

You can do the following to include variables in the prompt:

some_var='first line'
read -p "$some_var"$'\n'"second line " user_input
echo $user_input

(I wanted to make this a comment to Nelson's answer, but I could not have newlines for code readability.)

jbrock
  • 111
  • 3
  • thank you!!! Along with the newlines, I needed a way to insert variables into the prompt, and none of the other solutions mentioned this. Very much appreciated!!! – fungtional Aug 16 '23 at 16:16