Skip to content

Shortest way to swap two files in bash

An answer to this question on Stack Overflow.

Question

Can two files be swapped in bash?

Or, can they be swapped in a shorter way than this:

cp old tmp
cp curr old
cp tmp curr
rm tmp

Answer

This is what I use as a command on my system ($HOME/bin/swapfiles). I think it is relatively resilient to badness.

#!/bin/bash
if [ "$#" -ne 2 ]; then
  me=`basename $0`
  echo "Syntax: $me <FILE 1> <FILE 2>"
  exit -1
fi
if [ ! -f $1 ]; then
  echo "File '$1' does not exist!"
fi
if [ ! -f $2 ]; then
  echo "File '$2' does not exist!"
fi
if [[ ! -f $1 || ! -f $2 ]]; then
  exit -1
fi
tmpfile=$(mktemp $(dirname "$1")/XXXXXX)
if [ ! -f $tmpfile ]; then
  echo "Could not create temporary intermediate file!"
  exit -1
fi
# move files taking into account if mv fails
mv "$1" "$tmpfile" && mv "$2" "$1" && mv "$tmpfile" "$2"