Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 635
Gareth A. Lloyd Avatar asked Feb 03 '12 19:02

Gareth A. Lloyd


1 Answers

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.

like image 167
Kevin Avatar answered Sep 23 '22 04:09

Kevin