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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8725925/
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-08-06 03:54:43  来源:igfitidea点击:

How to read just a single character in shell script

linuxshellioksh

提问by footy

I want similar option like getche()in C. How can I read just a single character input from command line?

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

Using readcommand can we do it?

read命令可以吗?

采纳答案by Diego Torres Milano

In ksh you can basically do:

在 ksh 中,您基本上可以执行以下操作:

stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw

回答by SiegeX

In bash, readcan do it:

在 bash 中,read可以做到:

read -n1 ans

回答by fess .

read -n1works for bash

read -n1适用于 bash

The stty rawmode prevents ctrl-c from working and can get you stuck in an input loop with no way out. Also the man page says stty -rawis not guaranteed to return your terminal to the same state.

stty raw模式会阻止 ctrl-c 工作,并使您陷入输入循环而无路可走。此外,手册页说stty -raw不能保证将您的终端返回到相同的状态。

So, building on dtmilano's answerusing stty -icanon -echoavoids those issues.

因此,基于dtmilano 的答案usingstty -icanon -echo可以避免这些问题。

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

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

read_char char
echo "got $char"

回答by Sergey Gurin

read -n1

reads exactly one character from input

从输入中读取一个字符

echo "$REPLY"

prints the result on the screen

在屏幕上打印结果

doc: https://www.computerhope.com/unix/bash/read.htm

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

回答by Mirko Steiner

Some people mean with "input from command line" an argument given to the command instead reading from STDIN... so please don't shoot me. But i have a (maybe not most sophisticated) solution for STDIN, too!

有些人的意思是“从命令行输入”是一个给命令的参数,而不是从标准输入读取……所以请不要射击我。但是我也有一个(可能不是最复杂的)STDIN 解决方案!

When using bash and having the data in a variable you can use parameter expansion

使用 bash 并将数据保存在变量中时,您可以使用参数扩展

${parameter:offset:length}

and of course you can perform that on given args ($1, $2, $3, etc.)

当然,您可以在给定的 args ( $1, $2, $3, 等)上执行该操作

Script

脚本

#!/usr/bin/env bash

testdata1="1234"
testdata2="abcd"

echo ${testdata1:0:1}
echo ${testdata2:0:1}
echo ${1:0:1} # argument #1 from command line

Execution

执行

$ ./test.sh foo
1
a
f

reading from STDIN

从标准输入读取

Script

脚本

#!/usr/bin/env bash

echo please type in your message:
read message
echo 1st char: ${message:0:1}

Execution

执行

$ ./test.sh 
please type in your message:
Foo
1st char: F