Bash Script: Read One Character At A Time

In a Bash script, you can read one character at a time using the read command with the -n 1 option. Here’s an example:

#!/bin/bash

while true; do
read -n 1 char
case $char in
q) exit ;;
*) echo "You pressed the $char key" ;;
esac
done

This script reads one character at a time from standard input and then uses a case statement to handle the input. If the user presses the q key, the script exits. Otherwise, the script prints a message indicating which key was pressed.

The -n 1 option to the read command tells Bash to read only one character at a time. Without this option, read will read an entire line of input, waiting for the user to press the Enter key.

Note that if you want to read input from a file or a command output, you can redirect the input using <. For example, to read one character at a time from a file called input.txt, you could modify the script as follows:

#!/bin/bash

while read -n 1 char; do
case $char in
q) exit ;;
*) echo "You pressed the $char key" ;;
esac
done < input.txt

In this case, the read command is reading one character at a time from the input.txt file, rather than from standard input. The while loop will continue to read characters until it reaches the end of the file.

Leave a Comment