$random

I need to use the $RANDOM command to get a line from a list of lines in a file randomly.

file is
help
go
three
house
film

how do i randomly get one word without looking into the file?

You want to get lines from a file without reading the file :confused:

A possible solution to read lines randomly from a file :

$ cat words.sh
#!/usr/bin/bash

words_file=words.txt
words_count=$(wc -l $words_file | awk '{print $1}')

for ((i=1; i<=10; i+=1))
do
   word_number=$(($RANDOM % words_count + 1))
   word=$(awk 'NR=='$word_number words.txt)
   echo "$word_number => $word"
done

$ cat words.txt
help
go
three
house
film
datafile
man
save
words
red
blue
$ words.sh
1 => help
7 => man
6 => datafile
1 => help
9 => words
10 => red
4 => house
11 => blue
3 => three
7 => man
$

Jean-Pierre.

My problem is my program has to prompt a user to do a guess game. The user has to guess a letter from a word that the program randomly chooses and then set a number of lives.

If the user guesses a letter correctly, the letter is displayed within the correct position in the word.

i.e
pls enter your guess letter: -----

if the word is hello for example, the user enters e
then the output has to look like this

pls enter your guess letter:-e---

so each dash has to be replaced by the letter and if any guessed letter is wrong, a message should be displayed saying
wrong letter: you have 4 lives left

hello,

can someone tell me more about $RANDOM? where is it defined and how is it implemented?

thanks

$RANDOM is a built-in bash function that returns a random integer in the range 0 - 32767.

$RANDOM is not a function but a shell variable only found in ksh bash and zsh.

In ksh93 the range for the RANDOM variable is 0 - 2**15 and is generated by means of the rand(3) pseudo-random number generator. As an extra precaution, ksh93 checks to see that it never picks the same number twice in a row.