[英]How to read just a single character in shell script
I want similar option like getche()
in C. How can I read just a single character input from command line?我想要像 C 中的getche()
类似的选项。如何从命令行读取单个字符输入?
Using read
command can we do it?使用read
命令可以吗?
在 bash 中, read
可以做到:
read -n1 ans
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. stty raw
模式会阻止 ctrl-c 工作,并且会使您陷入输入循环而无路可走。 Also the man page says stty -raw
is not guaranteed to return your terminal to the same state.手册页还说stty -raw
不能保证将您的终端返回到相同的状态。
So, building on dtmilano's answer using stty -icanon -echo
avoids those issues.因此,基于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"
In ksh you can basically do:在 ksh 中,您基本上可以执行以下操作:
stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw
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
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.)当然,您可以在给定的参数( $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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.