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?
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?
In ksh you can basically do:
reads exactly one character from input
prints the result on the screen
doc: 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!
When using bash and having the data in a variable you can use parameter expansion
and of course you can perform that on given args (
$1
,$2
,$3
, etc.)Script
Execution
reading from STDIN
Script
Execution
In bash,
read
can do it:read -n1
works for bashThe
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 saysstty -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.