6

I am working in bash under Ubuntu 10.04 at the moment, but the solution would be interesting in other environments as well (e.g. Windows cmd.exe). I would typically rename the first file with a temporary name, rename the second file with the first name and finally rename the temporary file with the second name. Is there and idiom or program for doing this in one step?

Example (bash):

$ mv file1 tmp; mv file2 file1; mv tmp file2
2
  • This is a basic variable swap. :) – iglvzx Feb 21 '12 at 4:34
  • Sure, but wouldn't it be nice to just type swap file1 file2 instead. I guess I'll just right a bash script to do that. – Judge Maygarden Feb 21 '12 at 4:36
5

I created the shell script below to accomplish this task, but I'm still curious if there are standard methods already available.

#!/bin/sh
tmp=`mktemp`
mv $1 $tmp
mv $2 $1
mv $tmp $2

I named it swap, made it executable and placed in my path. That allows for the following syntax.

swap file1 file2
3
  • Uh, I didn't use a fixed name. See ( manpagez.com/man/1/mktemp ). – Judge Maygarden Feb 21 '12 at 14:49
  • My bad, I somehow read the backtcks as ". – Nifle Feb 21 '12 at 16:43
  • No problem. I don't do shell scripting often. So, your use of the PID variable ($$) was actually very helpful. ;) – Judge Maygarden Feb 21 '12 at 19:32
0

Try:

$ mv old_file tmp_file && mv current_file old_file && mv tmp_file current_file

As seen on SO https://stackoverflow.com/a/1115909/1478950

Safer, as you won't loose files if the initial mv fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.