Using read without triggering a newline action on

2019-02-16 20:46发布

问题:

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.

回答1:

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.