Jerico
Jerico

Reputation: 173

How to use new line character in bash?

I am trying to make a loop that will loop until the escape key is pressed but I have a struggle with printing the read message because if any key, except the enter key, it will continue to print in one line

Here is my code:

while : ; do
    read -n1 -r -p "Press esc key to continue...\n" key
    [[ $key != $'\e' ]] || break
done

It outputs Press esc key to continue...\n

Upvotes: 0

Views: 375

Answers (2)

Ben Van Camp
Ben Van Camp

Reputation: 136

I'd restructure just a little bit!

1.) The input message ("Press esc key to continue...") shouldn't have an embedded newline. This newline, I'm assuming, should appear after the user presses escape.

1a.) We also don't want user input popping up on the screen, so read -s (silently) after echoing -n (no newline) your input prompt.

Original:

read -n1 -r -p "Press esc key to continue...\n" key

Modified:

echo -n "Press esc key to continue..."; read -s -n1 -r key

2.) Now, when the user presses ESC, I believe you'd like to initiate a newline & exit the loop, so just echo AND break on the ESC key press. Boom.

2a.) On the issue of everything BUT an escape re-printing the message...Well, let's do a carriage return if the user DOESN'T hit escape, that way the message is printed in the same spot instead of on a new line!

Original:

[[ $key != $'\e' ]] || break

Modified:

if [[ $key == $'\e' ]];then echo;break; else echo -ne "\033[0K\r"; fi

Finished version:

   while : ; do
     echo -n "Press esc key to continue..."; read -s -n1 -r key
     if [[ $key == $'\e' ]];then echo;break; else echo -ne "\033[0K\r"; fi
   done

Testing it (a bunch of random NON-ESCAPE keys): enter image description here

Let me know if that works for you!

Upvotes: 0

anubhava
anubhava

Reputation: 784878

You can use $'...' string like you're using for detecting escape character already:

while : ; do
    read -n1 -r -p $'Press esc key to continue...\n' key
    [[ $key != $'\e' ]] || break
done

As per man bash:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences are \n, \t, \e etc.

Upvotes: 1

Related Questions