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
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.
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.
$ 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" }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With