5th February 2012

Automatically backing up files before making changes

Sunday, June 1st, 2008

It’s best practice (and common sense) to make a backup of a file before you edit it. Unfortunately it’s easy to forget to do this. We use this simple script below to make a time/date stamped copy of a file before launching the editor (in this case vim). We create it as /usr/local/bin/bvi.


#!/bin/bash
[[ -r $1 ]] && cp $1{,.`date +%Y%m%d-%H%M`} || echo "$1 is a new file"

vim $1

We then add the following two aliases to our ~/.bashrc file to make sure it’s run automatically when we call vim.

alias vi=/usr/local/bin/bvi
alias vim=/usr/local/bin/bvi

This isn’t a replacement for good version control of important files, but it’s a good safety net. It’s also worth noting that this can leave a lot of old copies of files laying about, so it’s work cleaning out old copies every now and again.

Parsing parameters in a BASH shell script

Monday, April 7th, 2008

This is a simple alternative to using getopts to parse parameters in a BASH shell script which makes use of the powerful parameter substitution functions in BASH. It should be sufficient for most scripts:


until [[ ! "$*" ]]; do
  if [[ ${1:0:2} = '--' ]]; then
    PAIR=${1:2}
    PARAMETER=`echo ${PAIR%=*} | tr [:lower:] [:upper:]`
    eval P_$PARAMETER=${PAIR##*=}
  fi
  shift
done

The script processes parameters in the format --name=value or --flag.

So, executing: ./example.sh --number=123 --show

Will result in the variable $P_NUMBER being set to “123″ and the variable $P_SHOW evaluating to true as it is set, albeit to a empty value.