script (copy)

I wanted a script to show a random quote from in every new terminal session. PHP is my language of choice. :) Save as “bashquote” and chmod 755 (rwxr-xr-x) to use (make sure the regexp looks exactly as below in preg_match_all()). The script only works in a Unix/Linux environment.


// Use http_proxy environment variable
stream_context_get_default(array('http' => array(
	'proxy' => str_replace("http://", "tcp://", getenv('http_proxy')),
	'request_fulluri' => true

// Quote cache location
$quotefile = getenv('HOME')."/.bashqdb";

// Only one instance accessing the cache at a time
$fp = fopen("/tmp/bashqdblock.".getenv('USER'),"wb");
if (!flock($fp, LOCK_EX))
	die("Couldn't obtain quote file lock!");

// Read cache

// If empty (or non-existing), fetch batch of quotes
if (!$quotes)
	$quotes = fetchQuotes();

// Select the first quote for display and remove it from array
$quote = $quotes[0];

// Massage the text for display
$quote = html_entity_decode($quote);
$quote = str_replace("<br />","n",$quote);

// Output
echo $quote."n";

// If that was our last, fetch a new batch
if (count($quotes) == 0)
	$quotes = fetchQuotes();

// Write the cache back
file_put_contents($quotefile, implode("n", $quotes));

// Function for fetching a batch of suitable quotes, returns an array
function fetchQuotes() {
	$matches = array();
	$source = file_get_contents("");
	preg_match_all("/<p class="qt">(.+?)</p>/si", $source, $matches);
	$quotes = array();
	foreach ($matches[1] as $match) {
		$quotes[] = str_replace("n","",$match);
	return $quotes;
Comments are closed.