Tag Archives: script

Ubuntu: Get Yesterday’s Date for a Bash Script CodeUnit 10 JAN 2011

Date work often plays an important part in automated bash scripts, and as such, it is pretty useful to be able to calculate yesterday’s date for your variable work.

Now we know in order to get the current date we could use this:

NOW="$(date +"%Y/%m/%d")"

Using this info, we find that it is remarkably simple to get yesterday’s date on any Linux system with:

YESTERDAY="$(date -d 'yesterday' +%Y/%m/%d)"

There are a range of other date manipulating strings available, including things like “3 days ago”, “next Monday”, “2 months”, etc, most of which can be found on the info date entry.

Nifty.

A Quick Guide to Bash Shell Scripting CodeUnit 23 AUG 2010

I stumbled across this gem of a quick guide to Bash shell scripting over at some or other forum and so as not to lose this valuable resource for my later use, I’ve decided to duplicate it here and thus save it for prosperity.

Common environment variables

PATH – Sets the search path for any executable command. Similar to the PATH variable in MSDOS.

HOME – Home directory of the user.

MAIL – Contains the path to the location where mail addressed to the user is stored.

IFS – Contains a string of characters which are used as word seperators in the command line. The string normally consists of the space, tab and the newline characters. To see them you will have to do an octal dump as follows:

$ echo $IFS | od -bc

PS1 and PS2 – Primary and secondary prompts in bash. PS1 is set to $ by default and PS2 is set to ‘>’ . To see the secondary prompt, just run the command :

$ ls |

… and press enter.

USER – User login name.

TERM – indicates the terminal type being used. This should be set correctly for editors like Vim to work correctly.

SHELL – Determines the type of shell that the user sees on logging in.

Note: To see what are the values held by the above environment variables, just do an echo of the name of the variable preceeded with a $. For example, if I do the following:

$ echo $USER
ravi

… I get the value stored in the environment variable USER.

Continue reading

Ubuntu: A Bash Script to Backup All MySQL Databases Running on a Server CodeUnit 28 JUL 2010

The following bash script is written to automate the process of backing up all your various MySQL databases running on either a local or remote MySQL server, using the useful mysqldump utility to do the actual backups.

What the script does is pretty simple to understand really.

First, you define all your server connections. Then it queries the server to find out which databases are currently running in the MySQL Server instance. Armed with this list, it runs through them all (ignoring the ones you specified on the ignore list) and pulls down a mysqldump of each database, gzipping it to its final backup file name.

Simple eh? So let’s see it then:

#!/bin/bash
MyUSER="mysql_user_account"
MyPASS="mysql_user_account_password"
MyHOST="localhost"

# Linux bin paths, change this if it can't be autodetected via which command
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
CHOWN="$(which chown)"
CHMOD="$(which chmod)"
GZIP="$(which gzip)"

# Backup Dest directory, change this if you have someother location
DEST="/var/mysql_backups"

# Main directory where backup will be stored
MBD="$DEST/sql_dumps"

# Get hostname
HOST="$(hostname)"

# Get data in dd-mm-yyyy format
NOW="$(date +"%Y%m%d-%H%M%S")"

# File to store current backup file
FILE=""

# Store list of databases
DBS=""

# DO NOT BACKUP these databases
IGGY="test"

[ ! -d $MBD ] && mkdir -p $MBD || :
# Get all database list first
DBS="$($MYSQL -u $MyUSER -h $MyHOST -p$MyPASS -Bse 'show databases')"

echo "Launching backup script at $(date)"

for db in $DBS
do
    skipdb=-1
    if [ "$IGGY" != "" ];    then
        for i in $IGGY        do
            [ "$db" == "$i" ] && skipdb=1 || :
        done
    fi

    if [ "$skipdb" == "-1" ] ; then
	FILE="$MBD/$db.$MyHOST.$NOW.sql.gz"
        # do all inone job in pipe,
        # connect to mysql using mysqldump for select mysql database
        # and pipe it out to gz file in backup dir
	echo "Starting backup process for $db (espreports.com) [$(date)]"
	$MYSQLDUMP --opt --compress --single-transaction -u $MyUSER -h $MyHOST -p$MyPASS $db | $GZIP -9 > $FILE
	echo "-- Complete ($FILE) [$(date)] --"
    fi
done

echo "Backup script completed execution at $(date)"

And we’re done. Nifty. (And damn useful to boot!)

Ubuntu: Executing a PHP Script file from the Command Line CodeUnit 18 JUN 2010

If you work as a web developer with PHP and all of a sudden you need a script to do something specific for you on a system (say as a cron job or such), there’s no real need to switch to another scripting language like Perl or Python if good old PHP will do the trick!

True, we could always call the PHP script via a WGET call to the localhost server and let our webserver (say Apache) handle the process, but in this case I specifically want to run the PHP file like I would any other bash script.

So how do we do it then?

Well PHP ships with a handy command line tool which has a whole lot of functionality built into it (like checking a file’s syntax with the -l switch for example) and one of its abilities is to interpret and execute a PHP script.

To do this, you feed it the control parameter of -f together with the script path and Bob’s your uncle. If you want to expand upon this and force the PHP script to be executed within the contraints supplied by a php.ini file, you simply specify the .ini file to use with a control switch of –php-ini.

So where are these files stored then?

Well the default PHP installation folder generally is the /etc/php5 folder and more often than not, you’ll locate your php.ini file sitting under /etc/php5/apache2/php.ini. The PHP command is usually added to your environment on install, meaning that executing a PHP script from the command line is as simple as running:

php –php.ini /etc/php5/apache2/php.ini -f synchronize_script.php

…from anywhere on your system. Useful, isn’t it? :)

Javascript Debug Window Script CodeUnit 07 JUN 2010

I found this little snippet of code floating around the Internet and despite its age, it still proves to be quite a handy little guy to have around when you are looking to quickly pop in a debug window in order to test some values against when in the middle of debugging some of that existing code of yours.

The premise for the script is pretty simple. Create a popup window and direct all debug comments into the new “debug” window, meaning that your site display remains clean and tidy but at the same time you’re are getting all the hidden variable values you really care about.

So no more print_r and annoying alerts to break the flow of your web application in other words! :P

// Show the debug window
function showDebug() {
  window.top.debugWindow =
      window.open("",
                  "Debug",
                  "left=0,top=0,width=300,height=700,scrollbars=yes,"
                  +"status=yes,resizable=yes");
  window.top.debugWindow.opener = self;
  // open the document for writing
  window.top.debugWindow.document.open();
  window.top.debugWindow.document.write(
      "Debug Window
n");
}

// If the debug window exists, then write to it
function debug(text) {
  if (window.top.debugWindow && ! window.top.debugWindow.closed) {
    window.top.debugWindow.document.write(text+"n");
  }
}

// If the debug window exists, then close it
function hideDebug() {
  if (window.top.debugWindow && ! window.top.debugWindow.closed) {
    window.top.debugWindow.close();
    window.top.debugWindow = null;
  }
}

To use is pretty simple really. At the start of your page, generate the debug window by calling showDebug(). Then, whenever you want to print something out, simply make use of the debug function, a little like this: debug(“this is a debug message”). Finally, if you are a purist, you may as well close your popup debug window by using hideDebug().

Of course, today’s awesome tools like Firefox’s plugin extraordinaire Firebug and even Internet Explorer’s built in debugger makes debugging Javascript pretty simple, but still, it remains pretty useful when you want to do something yourself and that little something you want to check doesn’t quite fall under the auspices of the existing tools at hand! :)

PHP: How to add a Hour to the Current Time CodeUnit 23 FEB 2010

Adding an hour to the current time turns out to be pretty easy thanks to the fantastic strtotime PHP function.

For example, should we wish to grab the hour that follows on from the current hour, we can simply make use of the code sample at the bottom of this entry.

This code snippet will echo out the following hour in 24-hour format, meaning that if the time was say currently 09:47, the script would echo out 10:

echo date('H',(strtotime("+1 hour"));

As easy as that.

SMS Server Tools 3: Send a Blank SMS using a PHP Script CodeUnit 25 JAN 2010

SMS Server Tools 3 is a great little SMS Gateway software which you can pair up nicely with some PHP scripts in order to send and receive SMSes.

Today’s little trick shows you how to send a blank (i.e. no text body) SMS using a PHP script to generate the outgoing spool file.

//$body is SMS text body | $phone is number being sent to
$handle = fopen('/var/spool/sms/outgoing/filesendname, "w");
$body = stripslashes(urldecode($body));
fputs($handle, "To: +$phonen");
fputs($handle, "Alphabet: ISO8859-15n");
fputs($handle, "n");
if (strlen($body) > 0)
{
    fputs($handle, "$body");
}
else
{
    fputs($handle, "n");
}
fclose($handle);

What the script does is actually pretty simple at heart. The first step is to create a new file handle in which to store the SMS contents, this file being created in the outgoing spool folder specified by your SMS3 configuration. Then you simply insert the correct text into the file, ensuring you keep strictly to the format used in the example above. The only little trick is that in order for it to process correctly when it comes to blank SMSes, you need to insert a new line n character to replace what would have been the SMS body.

And Bob’s your uncle.

Related Link: http://smstools3.kekekasvi.com/