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
How to read just a single character in shell script
提问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 read
command 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, read
can do it:
在 bash 中,read
可以做到:
read -n1 ans
回答by fess .
read -n1
works for bash
read -n1
适用于 bash
The stty raw
mode prevents ctrl-c from working and can get you stuck in an input loop with no way out. Also the man page says stty -raw
is not guaranteed to return your terminal to the same state.
该stty raw
模式会阻止 ctrl-c 工作,并使您陷入输入循环而无路可走。此外,手册页说stty -raw
不能保证将您的终端返回到相同的状态。
So, building on dtmilano's answerusing stty -icanon -echo
avoids 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
在屏幕上打印结果
回答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