-1

I have this script,

#!/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

The variable $guess was suppossed to return a 2 digit number, but returns null. Running the game with sh guess.sh and pressing return, returns congrats instead of the correct number being guessed. Where am I going wrong

atheros
  • 256

2 Answers2

5

Use bash instead of sh

guess=$(echo $RANDOM | cut -b 1-2)
             ^-----^ SC3028: In POSIX sh, RANDOM is undefined.
Rabin
  • 3,883
  • 1
  • 22
  • 23
  • 1
    read -p is furthermore not guaranteed to work in non-bash scripts. You may also want to comment on the way they run the script recursively... – Kusalananda Dec 29 '20 at 19:51
  • Running this with ./guess.sh(provided that declare #!/bin/bash) runs fine, however, sh guess.sh shows faulty result. – atheros Dec 29 '20 at 19:52
  • That because you overwrite the shell which execute the script – Rabin Dec 29 '20 at 19:53
  • Okay, I'm upvoting both of the answers, Adding #!/bin/bash solved the issue, if ran with ./guess.sh. – atheros Dec 29 '20 at 19:56
2

The -b flag in cut is for bytes, try the -c flag for characters instead.

I would also suggest changing the shebang to #!/bin/bash or #!/usr/bin/env bash. Otherwise it will use the system default (on Ubuntu this is dash) using POSIX mode.

shiftF5
  • 21