1

In bash I want to prompt user for input in a script. Lets say the input is:

#!/bin/bash

echo "Please enter a number."
read NUM

# User enters "12345678"

How can I use the next command to generate a random number and then check to see if that number is the same as one of the digits of the user input?

tr -dc '0-9' </dev/urandom | head -c 1

I want to be able to check to see if the generated number matches any of the digits in the user input that I choose. I want to be able to compare the generated number with any of the digits in the user input without having to make the user input be separate variables.

(edit) If the input is: 12345678 I want the generator to generate numbers until the 1's place is matched, then the 10's place, then the 100's place and so on until there is a full string match. I need the tr command output to be compared with a single place value at a time in sequence.

How would I do this in bash?

1 Answer 1

1

I'm not sure if I understood what you need. Please tell me if the following code doesn't solve your problem.

# !/bin/bash

echo "Please enter a number."
read NUM

while read -n1 DIGIT; do
    echo "Digit: $DIGIT"
    while true; do
        RND=$((RANDOM%10))
        if [[ "$RND" == "$DIGIT" ]]; then
            echo "$RND matches.";
            break;
        else
            echo "$RND doesn't match.";
        fi
    done
done < <(echo -n "$NUM" | rev)

Output example:

Please enter a number.
537
Digit: 7
4 doesn't match.
6 doesn't match.
7 matches.
Digit: 3
3 matches.
Digit: 5
9 doesn't match.
7 doesn't match.
0 doesn't match.
5 matches.

You can replace RND=$((RANDOM%10)) with RND="$(tr -dc '0-9' </dev/urandom | head -c 1)", but the former is faster.

The following code may be enough for you:

# !/bin/bash

echo "Please enter a number."
read NUM

RND=$((RANDOM%10))

if [[ $NUM == *"$RND"* ]]; then
  echo "It matches";
fi
1
  • I figured out the solution on my own by comparing the nth number of $NUM to an array from {0..9}.
    – Yokai
    Jul 17, 2016 at 2:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .