如何在shell脚本中只读取一个字符

foo*_*oty 22 linux io shell ksh

我想要像getche()C中的类似选项.如何从命令行只读取一个字符输入?

read我们可以使用命令吗?

Sie*_*geX 41

在bash中,read可以这样做:

read -n1 ans
Run Code Online (Sandbox Code Playgroud)

  • read -p"输入任何字符:" - n1 ans; echo -e"\n你输入了:$ ans" (2认同)

fes*_*s . 18

read -n1 适用于bash

stty raw模式可以防止ctrl-c工作,并且可以让你陷入输入循环而无法解决.另外,手册页说stty -raw不能保证将终端返回到同一状态.

因此,在dtmilano的答案基础上使用stty -icanon -echo可以避免这些问题.

#/bin/ksh
## /bin/{ksh,sh,zsh,...}

# read_char var
read_char() {
  stty -icanon -echo
  eval "$1=\$(dd bs=1 count=1 2>/dev/null)"
  stty icanon echo
}

read_char char
echo "got $char"
Run Code Online (Sandbox Code Playgroud)

  • 这也适用于 `ash`(用“BusyBox v1.10.2”测试),以及“#!/bin/sh”在 debian 上是 `dash`。 (2认同)

Die*_*ano 10

在ksh你基本上可以做:

stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw
Run Code Online (Sandbox Code Playgroud)


Ser*_*rin 5

read -n1
Run Code Online (Sandbox Code Playgroud)

从输入中读取一个字符

echo "$REPLY"
Run Code Online (Sandbox Code Playgroud)

在屏幕上打印结果

文档:https : //www.computerhope.com/unix/bash/read.htm