How to read just a single character in shell scrip

2019-04-12 15:21发布

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

Using read command can we do it?

标签: linux shell io ksh
5条回答
乱世女痞
2楼-- · 2019-04-12 15:59

In ksh you can basically do:

stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw
查看更多
何必那么认真
3楼-- · 2019-04-12 16:07
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

查看更多
在下西门庆
4楼-- · 2019-04-12 16:11

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!

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

${parameter:offset:length}

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

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
查看更多
Rolldiameter
5楼-- · 2019-04-12 16:18

In bash, read can do it:

read -n1 ans
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-04-12 16:21

read -n1 works for 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.

So, building on dtmilano's answer using stty -icanon -echo avoids those issues.

#/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"
查看更多
登录 后发表回答