Bash: Swap contents of two files

How to swap contents of two files in any directory using bash?

Add a function that swaps content of two files in your .bashrc.

# swap: Swaps contents of two files
#    param1: the file to be swapped
#    param2: the file to be swapped
function swap() # swap 2 filenames around
   if [[ -e "$1" && -e "$2" ]]      # if files exist
      local TMPFILE=tmp.$$
      mv "$1" $TMPFILE
      mv "$2" "$1"
      mv $TMPFILE "$2"
      echo "Error: Make sure the files exist."

The function first tests if the files exist using the -e test operator. The if/then construct tests whether the exit status of the -e operator returns 0 (means true in UNIX). If it does, the commands following then are executed; otherwise, the commands following else are run. Then, the function makes a temporary copy of the first file (whose name/location is specified by the positional parameter, $1) The special parameter, $$, stores the process ID (or PID) of the script. This variable is usually used to have unique filenames. The function moves the second file to the first file ($2) and copies the temporary file into the second file. The result is that the contents of the files are swapped while their names are the same. So to undo swap, you can execute swap command again with the same parameters. Note that the temporary file gets deleted when the function exits and its declared local in the function. Also note that since we are testing for more than one condition, we need to have another pair of square brackets ([,]) surrounding the if condition.
So to be able to run this function anywhere using bash, you must source it, or simply add it to your .bashrc.

Some code borrowed from