Håvard Pedersen

En blogg om vår digitale hverdag og andre pretensiøse temaer :)

Bash.org script

I wanted a script to show a random quote from bash.org 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.

#!/usr/bin/php
<?php

// 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
$quotes = @file($quotefile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES | FILE_TEXT);

// 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];
unset($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("http://bash.org/?random1");
	preg_match_all("/<p class=\"qt\">(.+?)<\/p>/si", $source, $matches);
	$quotes = array();
	foreach ($matches[1] as $match) {
		$quotes[] = str_replace("\n","",$match);
	}
	return $quotes;
}
?>
Del med verden:
  • Facebook
  • Google Bookmarks
  • email
  • TwitThis

2 Responses

  1. RandomiZed sier:

    Why did you write it in php?
    Not sure this qualifies as a bash script as long as the whole thing is put in a .

    You can easily just rename the file and run in on a webpage.

    Should try doing it in actual bash, and not use another language hidden in a .sh script.

  2. RandomiZed sier:

    omg. nevermind.
    lol : D

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>