flybywire flybywire - 4 months ago 48
Linux Question

Shortest way to swap two files in bash

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


Add this to your .bashrc:

function swap()         
    local TMPFILE=tmp.$$
    mv "$1" $TMPFILE
    mv "$2" "$1"
    mv $TMPFILE "$2"

If you want to handle potential failure of intermediate mv operations, check Can Bal's answer.

Please note that neither this, nor other answers provide an atomic solution, because it's impossible to implement such using Linux syscalls and/or popular Linux filesystems. For Darwin kernel, check exchangedata syscall.