$(echo $RANDOM | cut -b 1-2) 在 shell 脚本中返回空行

$(echo $RANDOM | cut -b 1-2) 在 shell 脚本中返回空行

我有这个脚本,

#!/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/bashor #!/usr/bin/env bash。否则它将使用系统默认值(在 Ubuntu 上是dashPOSIX 模式)。

相关内容