Quote:
Originally Posted by Dafydd
Using
Code:
function randomline() {
retValue=$(shuf -i 1-9 -n 1 $1)
}
How do I make sure that when shuf is seeded it is not seeded with a zero?
|
The above shuf command is not correct. If you use the
-i LOW-HI option you cannot use an input file. You either choose to take input from a file or set the input with the -i option:
Code:
shuf -n 1 infile # take 1 random line from infile
shuf -i 1-9 -n 1 # pick 1 number from the 1 to 9 range
The only way shuf can produce an empty line is if there is an empty line in the input file. I tried to reproduce this ad nauseam and I never get an empty/zero return.
$RANDOM generates a number in the 0 to 32767 range, but you can force it to start from 1 instead by doing the following:
Code:
$((RANDOM%30+1)) # This print a random number in the 1 to 30 range (both included)
I've played around with the above script and it does what it is supposed to do.
Here's an alternative which includes some of the info given and a few other changes you might find interesting:
Code:
#!/bin/bash
# get random line
function randomline() {
retValue=$(shuf -n 1 $1)
}
# set counters
k=10
i=0
loop_count=10
while [ "$i" -lt "$loop_count" ]
do
# gig day (using RANDOM)
gigday=$(($RANDOM%30+1))
[ "$gigday" -lt "$k" ] && gigday="0$gigday"
# gig month (using shuf)
gigmonth=$(shuf -i 1-12 -n 1)
[ "$gigmonth" -lt "$k" ] && gigmonth="0$gigmonth"
# gig
gigyear=2013
gigartiswebsite="artistwebsite.html"
gigvenuwebsite="venuewebsite.html"
# gig artist
randomline "artists"
gigartist="$retValue"
# gig town
randomline "towns"
gigtowns="$retValue"
# store data
echo "$gigmonth"/"$gigday"/"$gigyear","$gigtowns","$gigartist","$gigartiswebsite","$gigvenuwebsite" >> singer
# increase counter
(( i++ ))
done
EDIT: Too focused on other stuff to remember printf, which makes it possible to get rid of the leading 0 check. Here's another variation of your script:
Code:
#!/bin/bash
# get random line
function randomline() {
retValue=$(shuf -n 1 $1)
}
# set counters
i=0
loop_count=10
while [ "$i" -lt "$loop_count" ]
do
# gig day (using RANDOM)
gigday=$(($RANDOM%30+1))
# gig month (using shuf)
gigmonth=$(shuf -i 1-12 -n 1)
# gig
gigyear=2013
gigartiswebsite="artistwebsite.html"
gigvenuwebsite="venuewebsite.html"
# gig artist
randomline "artists"
gigartist="$retValue"
# gig town
randomline "towns"
gigtowns="$retValue"
# store data
printf '%02d/%02d/%d,%s,%s,%s,%s\n' "$gigmonth" "$gigday" "$gigyear" "$gigtowns" "$gigartist" "$gigartiswebsite" "$gigvenuwebsite" >> singer
# increase counter
(( i++ ))
done
Here's a link to printf:
Bash printf syntax basics