Gareth A. Lloyd
Gareth A. Lloyd

Reputation: 1942

Using read without triggering a newline action on terminal

I currently have this

$PROMPT=">"
while read -p "${PROMPT}" line; do
  echo -en "\r"
  some_info_printout($line)
  echo -en "\n${PROMPT}"
done

which gives output like this

>typed input
INFO OUT ["typed input"]
>more text
INFO OUT ["more text"]
>

what I would like is to do a read and ignore the newline action such that preciding text can overwrite the existing line

INFO OUT ["typed input"]
INFO OUT ["more text"]
>

Any help would be appreciated.

Upvotes: 19

Views: 20835

Answers (2)

Näbil Y
Näbil Y

Reputation: 1650

Another solution to keep the cursor on the same line after echo could be to use \c escape character along with -e flag.

echo -e "Want to do something fun? (y/n) \c"
read -r
echo "You answered: $REPLY"

Note: It might be specific to some versions of echo: https://stackoverflow.com/a/7154820/2110909

Upvotes: 2

Kevin
Kevin

Reputation: 56049

The Enter that causes read to return necessarily moves the cursor to the next line. You need to use terminal escapes to get it back to the previous line. And the rest of your script has some problems anyway. Here's something that works, it should give you a better starting point:

#!/bin/bash -e

PROMPT=">"
while read -p "${PROMPT}" line; do
        echo -en "\033[1A\033[2K"
        echo "You typed: $line"
done  

\033 is an Esc; the \033[1A moves the cursor to the previous line, \033[2K erases whatever was on it.

Upvotes: 21

Related Questions