bash 使用 read 而不在终端上触发换行操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9134638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:29:26  来源:igfitidea点击:

Using read without triggering a newline action on terminal

bashterminalnewline

提问by Gareth A. Lloyd

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 readand ignore the newline action such that preciding text can overwrite the existing line

我想要的是做一个read并忽略换行操作,这样 preciding 文本可以覆盖现有的行

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

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Kevin

The Enterthat causes readto 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:

Enter导致read以一定返回将光标移动到下一行。您需要使用终端转义将其返回到上一行。无论如何,您的脚本的其余部分都有一些问题。这是有效的方法,它应该为您提供一个更好的起点:

#!/bin/bash -e

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

\033is an Esc; the \033[1Amoves the cursor to the previous line, \033[2Kerases whatever was on it.

\033是一个Esc;在\033[1A将光标移动到上一行,\033[2K擦除无论是就可以了。