I am trying to create a bash script where I ask for a users age and then the script returns two numbers that sum to their age.
I tried
read -p "Enter your age: " age
echo $RANDOM $RANDOM="$age"
When running this it printed random numbers that do not equal the age that the user inserted. I was expecting it to print two random numbers that added up to their age.
CodePudding user response:
#!/bin/bash
# Ask the user for their age
echo -n "Enter your age: "
read age
# Generate two random numbers that sum up to the user's age
num1=$((RANDOM % age))
num2=$((age - num1))
# Print the two numbers
echo "The numbers are: $num1 and $num2"
The script above first asks for the user's age using the echo
and then reads and saves the age using the read
. It will then print two random numbers that when added together equals to the age that the user entered.
CodePudding user response:
Well, you can't use 2 random numbers if their sum must be equal to the given age; one is enough:
read -p "Enter your age: " age
rand=$(( (RANDOM % (age-1)) 1 )) # => in the range [1..age-1]
echo "$rand $(( age - rand )) = $age"