0

I am writing a shell script on my Linux machine, and I'm trying to figure out a good way to write a function that I could call that would set a variable, let's call it $variable, to a random number between 1 and 466,550. Of course I could write;

shuf -i 1-466550 -n 1

And it'll do the trick, but how could I write this in a function to have it set my variable, $variable, to that random number (until the function is called again, at which case it picks another random integer from 1-466,550)?

  • 1
    Are you asking [How do I assign the output of a command to a variable?](https://askubuntu.com/questions/323162/how-do-i-assign-the-output-of-a-command-to-a-variable) – steeldriver Sep 22 '20 at 18:45

2 Answers2

0

I would highly recommend reading through a bash scripting guide. I usually recommend Bash Scripting for Beginners and Advanced Bash-Scripting Guide, though they have not been updated for a couple of years...

With that said, here's an example of how it could be done.

#!/usr/bin/env bash

generate_random() {
    shuf -i 1-466550 -n 1
}

variable="$(generate_random)"
echo "random number: ${variable}"
variable="$(generate_random)"
echo "another random number: ${variable}"
mgor
  • 1,191
  • 7
  • 12
0

Generating a random number with bash $RANDOM variable:

#!/bin/bash

f(){
    echo $(((RANDOM * RANDOM) % 466550 + 1))
}
x=$(f)
echo $x