我希望有一个类似于C语言中getche()
的选项。如何从命令行读取单个字符输入?
我们可以使用read
命令来实现吗?
在bash中,read
可以实现:
read -n1 ans
read -n1
适用于bash。
stty raw
模式会阻止ctrl-c的使用并可能使您陷入输入循环中无法退出。此外,man页面上说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"
ash
(在“BusyBox v1.10.2”上进行了测试),以及在debian上dash
为“#!/bin/sh”。 - Sam\n
上失败了。修复方法是:eval "$1=\$'\\x$(dd bs=1 count=1 2>/dev/null | xxd -p)'"
。 - undefinedstty icanon echo
破坏了read
的行编辑功能。修复方法:使用stty sane
。 - undefined在ksh中,您基本上可以执行:
stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw
${parameter:offset:length}
我可以帮助你在给定的参数 ($1
, $2
, $3
等) 上执行操作。
脚本
#!/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
$ ./test.sh foo
1
a
f
脚本
#!/usr/bin/env bash
echo please type in your message:
read message
echo 1st char: ${message:0:1}
$ ./test.sh
please type in your message:
Foo
1st char: F
read -k1 ans"?输入任意字符:" ; echo -e "\n你输入的是:$ans"
应该与bash中dimir的评论具有相同的效果。 - Friartek