[svlug] Extended Keyboard Input Utility For Bash?

Tim Utschig tim at tetro.net
Sun Mar 25 14:47:37 PDT 2007


On Sat, Mar 24, 2007 at 05:21:04PM -0700, Mark S Bilk wrote:
> On Fri, Mar 23, 2007 at 08:13:19PM -0700, Tim Utschig wrote:
> >Maybe use [n]curses' keyname() function?
> 
> Thanks, Tim.  I don't want to use ncurses because I'm just 
> trying to get the extended keys, from a program that would
> be called once per keystroke in a bash script.  So I don't
> want to initialize the terminal (window) for ncurses and 
> then deinitialize it for each key (or even figure out how to 
> do that).

If you're OK with only the current line being destroyed, this should
work:


tim at x1000:~/tmp$ cat getkey.c
#include <unistd.h>
#include <curses.h>

int main() {
    int     c, orig_out;
    char   *name;
    WINDOW *wp;

    /* save old stdout and make stdout a dup of stderr so that curses */
    /* will work correctly when this program is called from a script  */
    /* like KEY=`getkey`                                              */
    orig_out = dup(1);
    dup2(2, 1);

    /* use a single line, leave the rest of the screen alone */
    filter();

    wp = initscr();
    noecho();
    nonl();
    cbreak();

    /* allow getch to capture multi-byte function key sequences */
    keypad(wp, TRUE);

    c = getch();
    endwin();

    dup2(orig_out, 1); /* restore original stdout */
    name = (char*)keyname(c);
    printf("%s\n", name != NULL ? name : "ERROR");

    return (name != NULL ? 0 : 1);
}
tim at x1000:~/tmp$ gcc -Wall -Werror -o getkey getkey.c -lcurses
tim at x1000:~/tmp$ cat t.bash
#!/bin/bash

echo "Key Pressed: \"`./getkey`\""
tim at x1000:~/tmp$ ./t.bash
Key Pressed: "KEY_PPAGE"
tim at x1000:~/tmp$ ./t.bash
Key Pressed: "KEY_LEFT"
tim at x1000:~/tmp$ ./t.bash
Key Pressed: "^M"
tim at x1000:~/tmp$


(The key I pressed in the last test run was [Enter]).

-- 
   - Tim Utschig <tim at tetro.net>




More information about the Svlug mailing list