Force user input in verbatim mode?

2019-04-02 11:33发布

问题:

I'm trying to any read user input keys in verbatim from Bash script, and then dump it into hex. That is:

read input
printf "%b" "$input" | xxd -p

If user press 2 keys a BACKSPACE, I would hope the output to be 617f, not empty.

How can I achieve that?

回答1:

This should work

#!/bin/bash

while true;do
    stty_state=$(stty -g) 
    #Save stty to reset to default
    stty raw isig -echo 
    #Set to raw and isig so nothing is interpretted and turn echo off so nothing is printed to screen.
    keypress=$(dd count=1 2>/dev/null)
    #Capture one character at a time
    #Redirect "errors" (from dd) output to dump
    keycode=$(printf "%s" "$keypress" | xxd -p)
    # Convert to hex
    stty "$stty_state"
    #Revert stty back
    printf "%s" "$keycode"
    #Print your key in hex
done

You can put a condition on the loop to exit the loop/program, otherwise you will need to use CTRLC` to exit.

This should print every key press except for CTRLC and CTRLz.