bash - 如何将$ RANDOM置于价值中?

时间:2016-12-09 22:40:15

标签: bash

bash的新手:

基本上我想将$ RANDOM的结果与用户通过' read'

给出的另一个值进行比较

更多信息的代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example" contenteditable="true">This is an example</div>

基本上我也想要一个if语句来查看该$ RANDOM值的结果是否等于用户键入的内容,例如:

echo $RANDOM % 10 + 1 | bc

有些东西!!

总结

如何制作它以便我可以将读取输入值与if [ [$RANDOM VALUE] is same as $readinput #readinput is the thing that was typed before then echo "well done you guessed it" fi

进行比较

想想我正在制作的节目“#GUESS THE NUMBER!&#39;

所有人都非常感谢:)

2 个答案:

答案 0 :(得分:1)

这里不需要bc - 因为你正在处理整数,本机数学会这样做。

printf 'Guess a number: '; read readinput

target=$(( (RANDOM % 10) + 1 )) ## or, less efficiently, target=$(bc <<<"$RANDOM % 10 + 1")

if [ "$readinput" = "$target" ]; then
  echo "You correctly guessed $target"
else
  echo "Sorry -- you guessed $readinput, but the real value is $target"
fi

但重要的是test命令 - 也称为[

test "$readinput" = "$target"

......与......完全相同。

[ "$readinput" = "$target" ]

...它可以比较两个值并退出,退出状态为0(if将视为真),如果它们匹配,或者非零退出状态(if否则将视为假。

答案 1 :(得分:1)

简短的回答是使用命令替换来存储您随机生成的值,然后询问用户猜测,然后比较两者。这是一个非常简单的例子:

#/bin/bash

#Store the random number for comparison later using command substitution IE: $(command) or `command`
random=$(echo "$RANDOM % 10 + 1" | bc)

#Ask the user for their guess and store in variable user_guess
read -r -p "Enter your guess: " user_guess

#Compare the two numbers
if [ "$random" -eq "$user_guess" ]; then
    echo "well done you guessed it"
else
    echo "sorry, try again"
fi

也许一个更强大的猜测程序将被嵌入循环中,这样它就会一直询问用户,直到他们得到正确的答案。您也应该检查用户是否输入了整数。

#!/bin/bash

keep_guessing=1

while [ "$keep_guessing" -eq 1 ]; do

    #Ask the user for their guess and check that it is a whole number, if not start the loop over.
    read -r -p "Enter your guess: " user_guess
    [[ ! $user_guess =~ ^[0-9]+$ ]] && { echo "Please enter a number"; continue; }

    #Store the random number for comparison later
    random=$(echo "$RANDOM % 10 + 1" | bc)

    #Compare the two numbers
    if [ "$random" -eq "$user_guess" ]; then
            echo "well done you guessed it"
            keep_guessing=0
    else
            echo "sorry, try again"
    fi
done