Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I need to swap filenames of two files (file and file_1). I'm using the following code for it.

mv file .phfile
mv file_1 file
mv .phfile file

This works but is very buggy, It sometimes even results in loss of data. Is there a better way to do this?

share|improve this question
Something you should be aware of and fear - any program that has an open file handle to either one of those files will retain the open file handle after the rename because it's pointing to the same inode that it had when it originally opened the file. Until all programs that have the files open close them, this will be the case and cause data corruption if you expect that renaming them 'breaks' any existing writer handles. –  synthesizerpatel Feb 28 '12 at 1:08

1 Answer 1

This is more robust:

mv "$file1" $TMPFILE && mv "$file2" "$file1" && mv $TMPFILE "$file2"

quoting is for preventing problems with spaces in filenames, it uses a tmp file and && make the following command run only if the preceding ended successfully.

share|improve this answer
How's this? file1=1stfile && file2=2ndfile && temp="$(mktemp -dp /mnt/sdcard)" && mv "$file1" $temp && mv "$file2" "$file1" && mv $temp/"$file1" "$file2". It works. Thanks for your input. –  Binoy Babu Feb 28 '12 at 1:47
see this stackoverflow.com/q/9475497/1068546 –  Binoy Babu Feb 28 '12 at 3:04
using mktemp is good; nice find –  guido Feb 28 '12 at 3:10
but running a command with && in java with runtime.exec() don't work. :( –  Binoy Babu Feb 28 '12 at 3:15
you have to quote your yourShellInput variable: String yourShellInput = " \"echo hi && echo ho\" "; or if ouy have double quotes in your command String yourShellInput = " 'echo hi && echo ho' "; –  guido Feb 28 '12 at 3:33

Your Answer


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.