我有这个脚本,
#!/bin/sh
guess=$(echo $RANDOM | cut -b 1-2)
read -p "Im thinking of a number, can you guess what it is? " number
case "$number" in
"$guess") echo "\nCongratulation number guessed corectly!"
exit 0
;;
*) echo "\nIncorrect number guessed, try again? [yes or no]"
read yesorno
case "$yesorno" in
"yes") sh guess.sh
;;
"no") echo "\nHave a nice day!"
exit 0
;;
*) echo "Invalid input"
exit 1
;;
esac
;;
esac
变量 $guess 应该返回一个 2 位数字,但返回 null。运行游戏并按sh guess.sh
回车键,返回祝贺而不是猜测正确的数字。我哪里出错了
答案1
使用bash
而不是sh
guess=$(echo $RANDOM | cut -b 1-2)
^-----^ SC3028: In POSIX sh, RANDOM is undefined.
答案2
cut 中的标志-b
用于字节,请尝试-c
使用字符标志。
我还建议将 shebang 更改为#!/bin/bash
or #!/usr/bin/env bash
。否则它将使用系统默认值(在 Ubuntu 上是dash
POSIX 模式)。