How to read only one character in a shell script

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

With the help of the team readcan we do this?

+14
source share
5 answers

In ksh, you can basically do:

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

In bash, readcan do this:

read -n1 ans
+29
source

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"
+15
0

" " , STDIN... , , . (, ) STDIN!

bash

${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

STDIN

#!/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
0

All Articles