views:

537

answers:

8

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
A: 

Surely mv instead of cp?

Alastair
+4  A: 
$ mv old tmp && mv curr old && mv tmp curr

is slightly more efficient!

Can Bal
...and doesn't `mv` your files into nirvana, if there is a problem with `tmp`. +1
Boldewyn
+1  A: 
mv old tmp
mv curr old
mv tmp curr
arturh
+6  A: 

You could simply move them, instead of making a copy.

#!/bin/sh
# Created by Wojtek Jamrozy (www.wojtekrj.net)
mv $1 cop_$1
mv $2 $1
mv cop_$1 $2

http://www.wojtekrj.net/2008/08/bash-script-to-swap-contents-of-files/

Zyphrax
A: 

using mv means you have one fewer operations, no need for the final rm, also mv is only changing directory entries so you are not using extra disk space for the copy.

Temptationh then is to implementat a shell function swap() or some such. If you do be extremly careful to check error codes. Could be horribly destructive. Also need to check for pre-existing tmp file.

djna
+4  A: 

Just to explain, the reason mv is much faster than cp, is that mv just changes directory entries, while cp actually copies the whole file contents.

anon
+8  A: 
tmpfile=$(mktemp $(dirname "$file1")/XXXXXX)
mv "$file1" "$tmpfile"
mv "$file2" "$file1"
mv "$tmpfile" "$file2"
cube
Upmod for using mktemp
Hasturkun
+3  A: 

Add this to your .bashrc:

function swap()         
{
    local TMPFILE=tmp.$$
    mv "$1" $TMPFILE
    mv "$2" "$1"
    mv $TMPFILE "$2"
}
Hardy
if mv "$2" "$1" fails, how do you detect this and roll back?
Michael Z