Dice in shell#
Today I was borrowing a board game from the lending library at Emerald City Comicon and it was missing its dice. We could have gotten some physical dice somewhere, but instead we decided to use the materials we had on hand. The people I was playing with agreed that we did not want to drain our phone batteries by using a dice app on our phones, but I had a laptop with me. So I wrote a dice app for the shell:
while true
do
reset
seq 1 6 | shuf -n1
seq 1 6 | shuf -n1
read
done
This rolls two six-sided dice every time you hit enter and
clears the screen before showing the result using reset
.
Better use of shuf
#
shuf
can generate the number sequence itself without using
seq
:
$ shuf -n1 --input-range=1-6
I didn't use that feature because I wanted to write the script quickly
without reading man
pages and didn't remember how to do it from
memory.
Accepting any key#
read_keypress.sh
:
#!/bin/sh
STTY=$(stty -g)
stty raw -echo
SEL=$(dd if=/dev/tty bs=1 count=1 2>/dev/null)
stty "$STTY"
echo "$SEL"
This script uses stty
to set the terminal to raw mode
(instead of using GNU Readline) and reads the next keypress
before restoring the terminal to its previous state. Effectively it
waits for a single keypress like read
waits for a line to be
typed.
Comments
Have something to add? Post a comment by sending an email to comments@aweirdimagination.net. You may use Markdown for formatting.
There are no comments yet.