How to Rename a Directory in Linux: mv & rename Examples
Learn rename a directory in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

11 min read
Learn rename a directory in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What mv Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Newcomers transitioning to the command line often look for a dedicated rmdir-style command to rename folders, only to discover that the standard way to rename a directory in linux is the mv (move) utility from GNU coreutils. In the UNIX filesystem model, renaming a directory and moving a directory within the same mounted filesystem are the exact same operation: updating a directory entry name in the parent directory while leaving the directory's inode and all files inside it untouched.
To rename a directory in Linux, use the mv (move) command followed by the current directory name and the new directory name: mv -vT old_dir_name new_dir_name. Including the -T (--no-target-directory) flag prevents mv from accidentally moving your source directory inside the destination directory if a folder with the new name already exists.
Because an in-filesystem rename only updates a parent directory pointer via the renameat2(2) system call, renaming a directory containing 500 gigabytes and millions of nested files completes instantaneously in less than a millisecond with zero disk data copying. However, a classic command-line pitfall awaits anyone who runs mv old_dir new_dir without understanding what happens when new_dir already exists.
In this guide, we explain the VFS inode mechanics of directory renaming, show why the -T (--no-target-directory) and -n (--no-clobber) flags are crucial for scripts, provide practical examples for single and batch directory renaming, and cover atomic symlink swap alternatives.
What mv Does and When to Use It
When you execute mv source_dir target_dir on the same mounted filesystem, mv invokes the Linux kernel renameat2(2) system call. Rather than recursively copying or touching the files inside source_dir, the kernel Virtual File System (VFS) atomically unlinks the old directory entry name from the parent directory's data block and links the new directory entry name to the exact same inode number. Because the inode number (st_ino) never changes, processes that already have open file descriptors or current working directories inside that folder continue operating without interruption.
By contrast, if source_dir and target_dir reside on two different mounted filesystems (for example, moving /tmp/build_cache on tmpfs to /var/cache/build on an ext4 disk), renameat2(2) returns EXDEV (Invalid cross-device link). When GNU mv receives EXDEV, it transparently falls back to recursively copying every nested directory, file, symlink, permission bit, and timestamp to the target filesystem before unlinking the original directory tree.
At the operating system level, mv (distributed in coreutils) interfaces with the Linux kernel through standard C library system calls and virtual filesystems. Understanding how mv resolves file descriptors, kernel structures, and exit status codes helps system administrators predict performance on high-load production servers.
Availability and Installation Across Linux Distributions
The mv utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether mv is installed and inspect which binary path and version your shell resolves:
type -a mv
mv --version 2>/dev/null || man -f mv
# Illustrative output (reviewed against documentation)
mv is /usr/bin/mv
mv (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils
# Arch Linux
sudo pacman -S --noconfirm coreutils
# Alpine Linux
sudo apk add --no-cache coreutils
Command Syntax, Arguments, and Exit Status Codes
mv [OPTION]... [-T] SOURCE_DIRECTORY TARGET_DIRECTORY
The standard syntax for renaming a single directory is mv [OPTIONS] [-T] OLD_DIR NEW_DIR. Understanding the difference between mv old_dir new_dir with and without -T is the most important rule in Linux directory management. Without -T, if new_dir does NOT exist yet, mv renames old_dir to new_dir; however, if new_dir ALREADY exists as a directory, mv moves old_dir INSIDE new_dir (creating new_dir/old_dir)!
Passing the -T (--no-target-directory) option eliminates this ambiguity: it instructs mv to always treat NEW_DIR as the exact target name rather than a container directory to move items into. Note also that you do NOT pass -r or -R when renaming or moving directories with mv—unlike cp and rm, mv handles directories natively.
0— The directory was renamed or moved successfully.1— Operational failure: permission denied on the parent directory (EACCES), source directory does not exist (ENOENT), or target directory already exists and is non-empty when using-T(ENOTEMPTY).2— Invalid command-line option or missing operand.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-T | --no-target-directory | Treats DEST as a normal target name rather than a parent container, preventing old_dir from being moved inside an existing new_dir. |
-v | --verbose | Prints a clear confirmation line showing the old path and the new path for every renamed directory. |
-n | --no-clobber | Refuses to overwrite an existing destination path; combine with -T (-nT) for completely safe non-destructive renames. |
-i | --interactive | Prompts for confirmation on stderr before overwriting an existing target. |
-b | --backup[=CONTROL] | Creates a backup of an existing destination before replacing it (using ~ suffix or numbered backups). |
-u | --update | Renames/moves only when the source is newer than the destination or when the destination is missing. |
--strip-trailing-slashes | --strip-trailing-slashes | Removes any trailing slashes from each SOURCE argument (useful when tab-completion appends / to directory names). |
For both interactive sysadmin work and automated deployment scripts, mv -nvT old_dir new_dir is the gold-standard invocation for renaming a directory. Here, -v confirms the rename on stdout, -T guarantees that old_dir will never be silently nested inside new_dir/old_dir if you run the command twice, and -n prevents overwriting an existing empty directory.
Additionally, remember that interactive shells frequently append a trailing slash when you press Tab to autocomplete a directory name (mv old_dir/ new_dir). While modern GNU mv handles trailing slashes on source directories gracefully during simple renames, adding --strip-trailing-slashes ensures consistent behavior when combining mv with advanced flags.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Rename a Directory Safely Using mv -vT
Rename a project directory from api-v1 to api-v2 in the current working directory while verifying that its inode number remains identical.
ls -di api-v1
mv -vT api-v1 api-v2
ls -di api-v2
# Illustrative output (reviewed against documentation)
1048592 api-v1
renamed 'api-v1' -> 'api-v2'
1048592 api-v2
Notice that the inode number (1048592) before and after mv -vT is unchanged, proving the kernel updated the directory entry pointer in place without copying any files.
2. Prevent Accidental Nesting When the Target Directory Name Already Exists
Compare what happens when you attempt to rename a directory to a name that already exists using -nvT versus standard mv.
mkdir -p staging_backup
mv -nvT app_staging staging_backup || echo "Rename blocked safely"
# Illustrative output (reviewed against documentation)
mv: cannot overwrite 'staging_backup': File exists
Without -T, running mv app_staging staging_backup would silently move your folder to staging_backup/app_staging. With -nvT, mv detects the collision immediately and leaves both directories untouched.
3. Rename a Directory Using Brace Expansion Shortcut in Bash
When renaming a directory tucked inside a long filesystem path, use Bash curly-brace expansion so you do not have to type the full parent path twice.
sudo mv -vT /var/www/releases/2026-10-22-{draft,published}
# Illustrative output (reviewed against documentation)
renamed '/var/www/releases/2026-10-22-draft' -> '/var/www/releases/2026-10-22-published'
Bash expands /var/www/releases/2026-10-22-{draft,published} into two full arguments before invoking mv, eliminating copy-paste typos in long paths.
4. Rename a Directory Containing Spaces or Special Characters
Quote directory names containing whitespace and replace spaces with hyphens for cleaner command-line handling.
mv -vT "Q4 Marketing Assets" q4-marketing-assets
# Illustrative output (reviewed against documentation)
renamed 'Q4 Marketing Assets' -> 'q4-marketing-assets'
Wrapping "Q4 Marketing Assets" in double quotes ensures the shell passes the entire name as a single argument rather than splitting it into three missing directory arguments.
5. Batch Rename Multiple Directories Using a Bash Loop
Loop over all subdirectories matching a glob pattern (*/ ensures only directories are matched) and replace spaces with underscores using Bash parameter expansion.
for dir in */; do
clean_base=$(basename "${dir}")
new_name="${clean_base// /_}"
if [ "${clean_base}" != "${new_name}" ]; then
mv -vnT -- "${clean_base}" "${new_name}"
fi
done
# Illustrative output (reviewed against documentation)
renamed 'Client Reports 2025' -> 'Client_Reports_2025'
renamed 'Server Logs Archive' -> 'Server_Logs_Archive'
The trailing slash in the glob pattern (*/) instructs the shell to match only directories and never regular files, while -- protects against directory names starting with a hyphen.
6. Batch Rename Directories with Regular Expressions Using rename
Use the Perl-based rename (prename) utility with -n (dry-run) and -v to preview and apply a regex transformation across multiple directories at once.
rename -n 's/^legacy_/v2_/' legacy_*/
rename -v 's/^legacy_/v2_/' legacy_*/
# Illustrative output (reviewed against documentation)
rename(legacy_auth/, v2_auth/)
rename(legacy_billing/, v2_billing/)
legacy_auth/ renamed as v2_auth/
legacy_billing/ renamed as v2_billing/
Always run rename with -n first to verify the regular expression match before executing the actual rename.
Real-World Workflows, Pipelines, and Shell Automation
Atomic Two-Directory Exchange Using python3 os.replace / renameat2 RENAME_EXCHANGE
The Linux kernel's renameat2(2) syscall supports an atomic RENAME_EXCHANGE flag that swaps two directories (such as live_app and next_app) in a single atomic kernel step with zero downtime. On modern GNU coreutils 9.2+, use mv --exchange; on older distributions, invoke the syscall or swap via an atomic symlink.
#!/usr/bin/env bash
set -euo pipefail
# Verify whether GNU mv supports --exchange (coreutils >= 9.2)
if mv --help 2>&1 | grep -q -- '--exchange'; then
mv -v --exchange app_live app_candidate
else
# Fallback: atomic symlink swap (recommended deployment pattern)
ln -sfn app_candidate current_tmp
mv -Tf current_tmp current
ls -ld current
fi
# Illustrative output (reviewed against documentation)
lrwxrwxrwx 1 deploy www-data 13 Oct 22 18:45 current -> app_candidate
Notice how mv -Tf current_tmp current atomically replaces the current symlink in a single renameat2() operation so web server requests never encounter a missing path.
Timestamped Directory Rotation Before Fresh Build Extraction
In build and backup scripts, safely rotate an existing directory by renaming it with an ISO-8601 UTC timestamp suffix before creating a fresh directory.
TARGET_DIR="/opt/builds/dist"
if [ -d "${TARGET_DIR}" ]; then
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
mv -vnT "${TARGET_DIR}" "${TARGET_DIR}.bak.${STAMP}"
fi
mkdir -pv "${TARGET_DIR}"
# Illustrative output (reviewed against documentation)
renamed '/opt/builds/dist' -> '/opt/builds/dist.bak.20261022T185000Z'
mkdir: created directory '/opt/builds/dist'
Renaming the old build directory out of the way takes less than a millisecond regardless of size, allowing the new deployment to proceed immediately while preserving an instant rollback copy.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding mv inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Never rename system directories (/bin, /lib, /lib64, /usr, /etc, or /var) on a running Linux host. Renaming /lib64 or /usr breaks the ELF dynamic linker (/lib64/ld-linux-x86-64.so.2), rendering every dynamically linked command—including mv, sudo, and ls—unable to start.
Under Linux POSIX permission semantics, your ability to rename a directory does NOT depend on the permissions or ownership of the directory being renamed! Instead, renaming a directory modifies the parent directory's entry table, so the caller only requires write (w) and execute (x) permissions on the parent directory.
The one critical exception is when the parent directory has the Sticky Bit (mode 1777, drwxrwxrwt, as on /tmp and /var/tmp) enabled: inside a sticky directory, the kernel prohibits unprivileged users from renaming or deleting any directory unless they own either that directory or the sticky parent directory.
GNU/Linux, BSD, and BusyBox Implementation Differences
While mv old_dir new_dir is universal across POSIX systems, the -T (--no-target-directory), -u (--update), --exchange, and -b (--backup) options are GNU coreutils extensions. On macOS and FreeBSD, mv does not support -T; instead, to prevent moving old_dir inside an existing new_dir in portable POSIX scripts, test [ ! -e "new_dir" ] before calling mv.
Additionally, remember that Linux exposes two completely different utilities named rename across distributions (covered in detail in Topic 18): Debian/Ubuntu ship the Perl regex rename tool (s/old/new/), while RHEL/Rocky/Fedora and Arch ship the util-linux rename tool (rename old_str new_str files...). Using mv inside a standard Bash loop avoids this cross-distro difference.
Troubleshooting Common Errors and Diagnostics
mv moved my folder INSIDE the target folder (new_dir/old_dir) instead of renaming it
Root Cause: A directory named new_dir already existed before you ran mv old_dir new_dir without the -T flag.
Resolution: Move the nested contents back out or remove the empty wrapper, and always pass -T (mv -vT old_dir new_dir) when your intent is strictly to rename a directory.
mv -v new_dir/old_dir/* new_dir/
rmdir new_dir/old_dir
mv: cannot move 'old_dir' to 'new_dir': Directory not empty
Root Cause: You ran mv -T old_dir new_dir (or tried to overwrite an existing directory), and the destination directory new_dir already exists and contains files.
Resolution: The Linux kernel rename(2) syscall refuses to overwrite a non-empty directory. Either rename or remove the existing new_dir first, or merge the two directories using rsync -a --remove-source-files old_dir/ new_dir/.
mv -vT new_dir new_dir.old
mv -vT old_dir new_dir
mv: cannot move 'dir_a' to 'dir_b': Permission denied
Root Cause: Even if you own dir_a, your user account lacks write (w) permission on the parent directory containing dir_a (or the destination parent directory).
Resolution: Check the permissions and ownership of the parent directory with ls -ld .. and run the command with sudo if renaming inside a root-owned path like /opt or /var/www.
ls -ld .
sudo mv -vT dir_a dir_b
Alternatives, Related Commands, and Related Tutorials
- mkdir Command in Linux: Create Directories & Parent Trees — Practical syntax, flags, and examples for
mkdir. - rename Command in Linux: Batch Rename Files with Regex — Practical syntax, flags, and examples for
rename. - chown Command in Linux: Change File & Directory Ownership — Practical syntax, flags, and examples for
chown. - How to Unzip Files in Linux: Extract, List & Exclude Guide — Practical syntax, flags, and examples for
unzip. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

UNIX and Linux System Administration Handbook, 5th Edition
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides

Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!