Is there anything equivalent to getch() in ksh?

I am writing a script in Korn Shell, where at one statement I want something like getch() used in C.

I want my while loop to be exited, if it sees that I have pressed ESC in Keyboard.

For eg.

while [[ getch() != 27 ]]
do
    print "Hello"
done

In my script this getch() != 27 won’t work. I want something there to be worked. Can anyone help?

Asked By: PriB

||

Use read

x='';while [[ "$x" != "A" ]]; do read -n1 x; done

read -n 1 is to read 1 character.

This should work in bash but you can check if it works in ksh

Answered By: bluefoggy
#!/bin/ksh

# KSH function to read one character from standard input
# without requiring a carriage return. To be used in KSH
# script to detect a key press.
#
# Source this getch function into your script by using:
#
# . /path/to/getch.ksh
# or
# source /path/to/getch.ksh
#
# To use the getch command in your script use:
# getch [quiet]
#
# Using getch [quiet] yields no output.

getch()
{
   STAT_GETCH="0"
   stty raw
   TMP_GETCH=`dd bs=1 count=1 2> /dev/null`
   STAT_GETCH="${?}"
   stty -raw

   if [[ "_${1}" != "_quiet" ]]
   then
       print "${TMP_GETCH}"
   fi
   return ${STAT_GETCH}
}
Answered By: user143235
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.