Shell – Best Way to Swap Filenames

filesrenameshellshell-script

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?

Best Answer

The renameat2 syscall on Linux systems, with the RENAME_EXCHANGE flag, should do exactly that, this is a cli tool that claims to use it.

Related Question