How does the mv command work for both renaming and moving files?
mv changes a file's name or location. Within the same file system it only updates the directory entry, so it is instant even for huge files; across file systems it copies the data and then deletes the original.
Explain it simply
In Linux, renaming and moving are the same act: changing a file's path. Think of a railway ticket: changing the name on it and changing the seat are both edits to the same record.
mv old.txt new.txt renames. mv new.txt ~/docs/ moves it. mv a.txt ~/docs/b.txt does both at once.
On the same file system, mv rewrites just the directory entry. A 50 GB file moves in a blink, and the inode stays the same. Across file systems (say, from your disk to a USB drive) mv must copy all the data and then delete the source, which takes time and can be interrupted midway.
By default mv overwrites silently. Use -i to prompt and -n to never overwrite.
Example
touch report.txt
mv report.txt report_final.txt # rename
mkdir archive
mv -i report_final.txt archive/ # move, ask before overwriting
ls archive
# report_final.txtWhat to say in the interview
"mv renames and moves by changing the path. On the same file system it only edits the directory entry, so it is instant; across file systems it copies then deletes. It overwrites by default, so I use -i or -n when unsure."
Common mistakes
- Forgetting that mv silently overwrites an existing destination file.