Shells: How to Respond to a Single Keystroke Within a Script

If you are using a newer Bourne-compatible shell such as (pd)ksh or bash, and have a modern terminal, you can take advantage of the -icanon stty mode to good effect. This mode allows your scripts to respond to a single keystroke rather than requiring the user to hit “return” after entering a character. This is useful for the familiar “Press any key to continue … ” type messages, but can also be used to provide control of programs.

Ensure that you restore your old stty settings before exiting. This is probably best achieved by using traps. The following script demostrates these concepts well, and gives the foundations of a Minesweeper-style grid, cursors, and cell-marking.