1

Below is the code i thought would create a random number between 0 to 50(Both included)

#!/bin/bash
var1=51
var=$RANDOM
echo $var
function rand(){
    local var1=$1
    local var2=$2
    local result=$(( var1 % var2 ))
    echo $result
}   
rand "var" "var1"

The first echo function is working fine its is showing a random number every time but the other echo function is always giving an output of zero

Bad_Panda
  • 15
  • 4
  • See [Random number from a range in a Bash Script](https://stackoverflow.com/q/2556190/4154375) and [Generating random number between 1 and 10 in Bash Shell Script](https://stackoverflow.com/q/8988824/4154375). Also see [BashFAQ/026 (How can I randomize/shuffle the order of lines in a file? ...)](https://mywiki.wooledge.org/BashFAQ/026), particularly the implementions of the `rand` function. – pjh May 22 '19 at 17:55

1 Answers1

1

Function to produce random number between 0 to 50

The function:

rand() { echo $((RANDOM % 50)); }

To your code:

  • bash uses strings
  • rand "var" "var1" pases string var and string var1 to the function
  • then local var1=$1 set's the variable var1 to be a local variable and the value of the var1 variable is the var string(!).
  • then local var2=$2 is equal to local var2="var1", it set's var2 variable value to the string "var1".
  • local result=$(( var1 % var2 )) is invalid. This is equal to local result=$(( "var" % "var1" )). You can't do calculus over "strings", it's meaningless.
  • Just pass the values of the variables rand "$var" "$var1" to the function.
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    Can we pass integers to functions in bash – Bad_Panda May 22 '19 at 12:39
  • 1
    There are no integers, per se. There are strings. An "integer" is a string (ie. it's representation in base 10). `var1=1` set's var1 to the string 1. When you do arithmetic expansion `$(( ... ))` then shell converts strings into numbers, does the arithmetic, and then converts number back to the string, to it's representation in base 10. You can "expand" the variable using `$`, ie. get it's value, ie. `rand "$var" "$var1"`. Please read online resources on that topic, ex. [this](https://www.shellscript.sh/variables1.html). – KamilCuk May 22 '19 at 12:42
  • I admit to not diving into the bash source to see how this is implemented, but you can give a variable an integer "attribute": `declare -i var`. Then if you try to assign a non-integer value to it, it just gets zero assigned instead. – glenn jackman May 22 '19 at 15:18