swapfn (Source)

#!/bin/bash
##---------------------------------------------------------------------------##
#
#   Program: swapfn
#   Author:  Brian <genius@groupbcl.ca> :)
#   Date:    March 2005
#
#   Given two file names (e.g. 'foo' and 'bar'), renames 'foo' as 'bar' and
#   'bar' as 'foo'.
#
##---------------------------------------------------------------------------##
# BUUS: This script is part of Brian's Useful Utilities Set

function die {
    [ -n "$1" ] && echo $1
    exit
}

[ $# != 2 ] && die "usage: swap file1 file2"

[ ! -f "$1" ] && die "swap: $1: not found"
[ ! -f "$2" ] && die "swap: $2: not found"
[ ! -w "$1" ] && die "swap: $1: cannot rename: no write permission"
[ ! -w "$2" ] && die "swap: $2: cannot rename: no write permission"

DIRNAME="$(dirname $1)"
TEMP_FN="$DIRNAME/__swap__.$$.temp"

mv "$1" "$TEMP_FN" || die "rename failed"
mv "$2" "$1"
RC=$?

if [ $RC = 0 ] 
then
    mv "$TEMP_FN" "$2"
    RC=$?
fi

if [ $RC != 0 ]
then
    echo "Rename failed ... restoring $1"
    mv "$TEMP_FN" "$1"
fi

# vim: tabstop=4