How to Rename a File in Bash: Simple Command and Examples
In bash, you rename a file using the
mv command followed by the current filename and the new filename. For example, mv oldname.txt newname.txt changes the file name from oldname.txt to newname.txt.Syntax
The basic syntax to rename a file in bash is:
mv <current_filename> <new_filename>
Here, mv is the move command that moves or renames files.
<current_filename> is the existing file name you want to rename.
<new_filename> is the new name you want to give the file.
bash
mv current_filename new_filename
Example
This example shows how to rename a file named report.txt to summary.txt.
bash
touch report.txt ls mv report.txt summary.txt ls
Output
report.txt
summary.txt
Common Pitfalls
Common mistakes when renaming files include:
- Trying to rename a file that does not exist, which causes an error.
- Overwriting an existing file without warning if the new filename already exists.
- Using incorrect paths or missing file extensions.
Always check if the file exists and be careful with filenames to avoid data loss.
bash
mv nonexisting.txt newname.txt # Error: mv: cannot stat 'nonexisting.txt': No such file or directory # Safe way to rename only if file exists if [ -f oldname.txt ]; then mv oldname.txt newname.txt; else echo "File does not exist."; fi
Output
mv: cannot stat 'nonexisting.txt': No such file or directory
File does not exist.
Quick Reference
| Command | Description |
|---|---|
| mv oldname newname | Rename file from oldname to newname |
| mv file.txt /path/to/newname.txt | Rename and move file to a different directory |
| mv -i oldname newname | Rename with prompt if overwriting existing file |
| mv -n oldname newname | Rename only if newname does not exist |
Key Takeaways
Use the mv command with current and new filenames to rename files in bash.
Check if the file exists before renaming to avoid errors.
Be cautious of overwriting files with the same new name.
Use options like -i for interactive prompts to prevent accidental overwrites.
You can rename and move files by specifying a new path in the new filename.