Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

2 Answers

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
share|improve this answer
    
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
add comment

Try:

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

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

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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