Linux shuf command

Posted on Tuesday, March 12, 2013




At least 2-3 times a year I come across a very useful linux command line tool that I think to myself… "How did I not know about this tool, it's so useful!"

This is command 'shuf'  is  one of those tools.

The need


I was writing a simple bash script last night to simply use curl to test out a restful service I am working on.    It’s a restful service that accepts a POST of a JSON file.   I wanted some of the number values in the JSON post to be randomized,  something like 12.34   22.14  some floaty looking number within a narrow range.

Doing a quick google search I came across the command line tool shuf.

Here are a couple of main pages detailing shuf  http://linux.die.net/man/1/shuf [1]


Here are some basic examples of what it can do.


> shuf -i 10-20


Will generate a list of the integers 10 to 20 inclusive and shuffle them up.



Or for my purposes I just wanted 1 number


> shuf -i 10-20 -n 1



Does the same thing but returns you  a number in the shuffled list



> shuf -i 10-20 -n 3



Returns 3 numbers

For my base script I wanted to create a random number like 12.21  (it was not important that it be really random)



#!/bin/bash


for ((i = 0; i < 20; i++))
do
   num=`shuf -i 1-20 -n 1`.`shuf -i 1-99 -n 1`
   echo $num
done






Here are the results of the program running.


[1]        shuf(1) - Linux man page
                Accessed 03/2013
[2]        shuf — generate random permutations
                Accessed 03/2013

2 comments:

  1. I like that. Having used Linux for more years than I want to remember I haven't come across this command. I usually find that having struggled to do something the hard way, someone has a command to do that. Thanks for the command.

    ReplyDelete
    Replies
    1. Not a problem. I will never cease learning linux, well maybe once I am 6 ft under... assuming there is not internet access there :)

      Delete