Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 915
flybywire Avatar asked Jul 12 '09 12:07

flybywire


People also ask

How do I swap the contents of two files in Linux?

To achieve that, we can concatenate the commands with “&&“. This is because the && operator ensures the later command gets executed only if the preceding command succeeds. As the output above shows, the command works. We've swapped the content of the two files.

What is ${ 2 in bash?

It means "Use the second argument if the first is undefined or empty, else use the first". The form "${2-${1}}" (no ':') means "Use the second if the first is not defined (but if the first is defined as empty, use it)". Copy link CC BY-SA 2.5.


2 Answers

$ 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" } 
like image 61
Can Bal Avatar answered Sep 27 '22 18:09

Can Bal


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.

like image 31
Hardy Avatar answered Sep 27 '22 20:09

Hardy