Unix shuf command line tool on Mac OS X using PHP

http://www.64Lines.com »» Unix shuf command line tool on Mac OS X using PHP «

Overview

When I was working with a quick playlist creator script a few days ago, I noticed that the shuf Linux tool was missing from my Mac. This tool allows you to pipe lines of input into it, which then outputs those same lines in a shuffled order. I decided to create a quick PHP shell script which should be placed into a file named "shuf" in one of your bin directories. Unix scripts that use shuf should then be able to run if they use the command is a filter.

I would like to note that the full shuf command supports a number of other options such as how many lines to output as well as using a file as input. Currently the script does not support those options - you should be able to recreate them by piping the output into the head command, and reading from a file can be done using the cat command.

Source Code

Shuf function PHP source code in 11 lines #!/usr/bin/php -n
<?php

// This is the key step of the script, takes in the input from stdin which can then be shuffled and output
$input = file_get_contents('php://stdin');

$input = explode("\n",$input);
shuffle($input);

echo implode("\n",$input);
?>

Check out the other 64Lines.com articles, tutorials, and tools

All article content is copyright of Michael Petrov, 2010©.
The source code presented in the articles is distributed as freeware, please feel free to use it in your own projects - both commercial and non commercial.
Valid HTML 4.01 TransitionalValid CSS!