Shortest way to swap two files in bash


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
1
55
7/12/2009 12:01:35 PM

Accepted Answer

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.

45
5/23/2017 12:02:53 PM

$ mv old tmp && mv curr old && mv tmp curr

is slightly more efficient!

Wrapped into reusable shell function:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon