How to Create a Bash Variable Like $Random

How to create a bash variable like $RANDOM

The special behavior of $RANDOM is a built-in feature of bash. There is no mechanism for defining your own special variables.

You can write a function that prints a different value each time it's called, and then invoke it as $(func). For example:

now() {
date +%s
}

echo $(now)

Or you can set $PROMPT_COMMAND to a command that updates a specified variable. It runs just before printing each prompt.

i=0
PROMPT_COMMAND='((i++))'

This doesn't work in a script (since no prompt is printed), and it imposes an overhead whether you refer to the variable or not.

Creating a custom random variable

As replied by JNevill, you can place it as a function in your bash profile :

function RANDOM(){
rando=$( head -100 /dev/urandom | tr -dc a-zA-Z0-9 | fold -w ${1:-15} | head -1 )
echo $rando
}

RANDOM
RANDOM 4
RANDOM 40

Output

17oxDRkl2O1c9iz
vfgZ
4xlVNyINrBj8XT04nkQWIVOTHAV51eVxtVNEyRW0

I added an optional first argument so you can control the length of the string as well.

How to generate a random string in bash?

This might be what you're looking for:

#!/bin/bash

chars='abcdefghijklmnopqrstuvwxyz'
n=10

str=
for ((i = 0; i < n; ++i)); do
str+=${chars:RANDOM%${#chars}:1}
# alternatively, str=$str${chars:RANDOM%${#chars}:1} also possible
done

echo "$str"

Your code was almost correct, except that you've missed the += operator. The += operator appends to the variable’s (str here) previous value. This operator was introduced into bash with version 3.1. As an aside note, it can also be applied to an array variable in order to append new elements to the array. It also must be noted that, in an arithmetic context, the expression on the right side of the += operator is evaluated as an arithmetic expression and added to the variable’s current value.

Random number from a range in a Bash Script

shuf -i 2000-65000 -n 1

Enjoy!

Edit: The range is inclusive.

Bash randomizing variables

How about something like this:

choices=(rock paper cissors) # Define an array with 3 choices
RPS=${choices[$RANDOM%3]} # Pick one at random

Discussion

Bash has a built-in variable called $RANDOM, which returns a random integer.

Generating random number between 1 and 10 in Bash Shell Script

$(( ( RANDOM % 10 )  + 1 ))

EDIT. Changed brackets into parenthesis according to the comment.
http://web.archive.org/web/20150206070451/http://islandlinux.org/howto/generate-random-numbers-bash-scripting

How to define dynamic variable in bash?

Make a function:

countPwd() {
ls | wc -l
}

Then call the function like any other command:

echo "There are $(countPwd) files in the current directory."


Related Topics



Leave a reply



Submit