Stepping through a random string character by char

2019-07-23 17:45发布

问题:

Working on this: A simple game to echo a random keyboard character; then have the user match that character as fast as possible (this is not implemented yet (obviously) but that's the goal) and keep a running total of the "correct matches."

#!/bin/bash
score=0
while true; do
clear
echo "$score"
character=$(</dev/urandom tr -dc '1234567890{}[]`~\/><!@#$%^&*()_+=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | head -c1)
echo "$character"
read -rsn1 input
if [ "$character" = "$input"]; then
  echo "[+]"
  score ++
  sleep 1
else
  echo "wrong!"
  score=0
  sleep 1
fi
done

Directly, my question is: Why am I getting

[: missing `]'

error. I have tried all variants of

if [ "$character" = "$input" ]; then

and second question: How would I properly ask my next question which is: given a long random string, how would one "explode" that string such that it has a space in between every character? I do not have the experience/lexicon to describe this operation.

Much appreciated!

回答1:

There must be a space before the ] like this:

if [ "$character" = "$input" ]; then

Also, to put bash in arithmetic mode, replace this line:

score ++

with:

((score ++))


标签: bash random