Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
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

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

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
share|improve this answer
Uh, I didn't use a fixed name. See ( ). – 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


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

As seen on SO

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

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .