Copying, Moving, and Renaming Files

Su Suriya Ravichandran Updated 06 Dec 2026
6 min read ·Lesson 17 of 205

Two commands handle nearly all file reorganization in Bash: cp copies items, and mv moves them. Renaming has no command of its own, because a rename is simply a move to a new name in the same directory. This lesson explains the rules both commands follow, how they treat existing files, and how to protect yourself from overwriting something by accident.

Understanding the Concept

Both commands take one or more sources followed by a destination:

cp  SOURCE...  DESTINATION
mv  SOURCE...  DESTINATION

What the destination means depends on what it is:

DestinationResult
An existing directoryEach source is placed inside that directory, keeping its name
A name that does not existThe single source is created (or renamed) under that new name
An existing fileThe file is replaced by the source, silently unless you ask otherwise

When you give more than one source, the destination must be a directory. Keeping this table in mind prevents most surprises.

The difference between the two commands is what happens to the original. cp leaves it in place and creates a second copy with its own data. mv leaves only one item, now at its new location or under its new name.

Copying Files with cp

Create a file and copy it:

printf 'hello\n' > a.txt
cp a.txt b.txt
ls
cat b.txt

Output:

a.txt  b.txt
hello

b.txt is a separate file with the same content. Editing one does not change the other.

Copying Into a Directory

If the last argument is a directory, the sources are copied into it:

cp -v a.txt c.txt
mkdir backup
cp a.txt b.txt c.txt backup/
ls backup

Output:

'a.txt' -> 'c.txt'
a.txt  b.txt  c.txt

The first command used -v (verbose) to show each copy it made. The trailing slash in backup/ is optional, but it adds a safety check: if backup did not exist, the slash would turn the command into an error instead of creating a file named backup:

cp a.txt nodir/

Output:

cp: cannot create regular file 'nodir/': Not a directory

Overwriting Existing Files

By default cp replaces an existing destination without asking:

printf 'new\n' > a.txt
cp a.txt b.txt
cat b.txt

Output:

new

The earlier content of b.txt is gone. Three options control this:

OptionBehavior
-iInteractive: ask before overwriting each existing file
-nNo clobber: never overwrite; skip files that already exist
-uUpdate: copy only when the source is newer than the destination

With -i, the command stops and waits for an answer:

cp -i a.txt b.txt

Interactive session:

cp: overwrite 'b.txt'? n

Typing y and pressing Enter replaces the file; anything else leaves it alone. Newer releases of GNU coreutils (9.3 and later) also accept --update=none as the clearer way to say "never overwrite", and the -n option prints a warning on coreutils 9.4 recommending it. Both forms keep the existing file:

echo A > ua
echo B > ub
cp --update=none ua ub
cat ub

Output:

B

Copying Directories

cp refuses to copy a directory unless you add -r (recursive), which copies the directory and everything inside it:

mkdir -p proj/src proj/docs
echo x > proj/src/main.c
echo y > proj/docs/readme.txt
cp proj proj2

Output:

cp: -r not specified; omitting directory 'proj'
cp -r proj proj2
find proj2 | sort

Output:

proj2
proj2/docs
proj2/docs/readme.txt
proj2/src
proj2/src/main.c

The destination name decides the result, just as in the table above. Because proj2 did not exist, it became a copy of proj. If the destination is an existing directory, the copy goes inside it:

mkdir dest
cp -r proj dest
find dest | sort

Output:

dest
dest/proj
dest/proj/docs
dest/proj/docs/readme.txt
dest/proj/src
dest/proj/src/main.c

Preserving Attributes

A plain copy gets a fresh modification time and the default permissions. The option -p keeps the original time, owner and permissions where possible, and -a (archive) preserves nearly everything and implies -r:

touch -d "2026-01-01 10:00" old.txt
cp old.txt copy1.txt
cp -p old.txt copy2.txt
ls -l --time-style=long-iso old.txt copy1.txt copy2.txt

Output (the date of copy1.txt is the day you run the command):

-rw-r--r-- 1 student student 0 2026-11-20 10:52 copy1.txt
-rw-r--r-- 1 student student 0 2026-01-01 10:00 copy2.txt
-rw-r--r-- 1 student student 0 2026-01-01 10:00 old.txt

Use cp -a when making backups of directory trees, so that times and permissions survive.

Moving and Renaming with mv

mv changes where an item lives or what it is called. Inside the same file system, it does not copy any data. It only updates the directory entry, so moving even a very large file is instant.

Renaming a File

Renaming means moving to a new name in the same directory:

mv a.txt renamed.txt
ls a.txt renamed.txt

Output:

ls: cannot access 'a.txt': No such file or directory
renamed.txt

The ls error confirms that a.txt no longer exists. Only renamed.txt does.

Moving Into a Directory

mv renamed.txt backup/
ls backup

Output:

a.txt  b.txt  c.txt  renamed.txt

You can move and rename in one step by giving a full destination path:

mv backup/renamed.txt backup/final.txt
mv backup/final.txt .
ls backup

Output:

a.txt  b.txt  c.txt

The first command renamed the file inside backup. The second moved it to the current directory, which is written .. The listing shows that final.txt has left backup.

Moving Several Items

With several sources, the last argument must be a directory:

mv b.txt c.txt dest/
ls dest

Output:

b.txt  c.txt  proj

Moving and Renaming Directories

Unlike cp, mv needs no -r. A directory is moved or renamed with the same syntax as a file:

mv proj proj_moved
ls -d proj*

Output:

proj2  proj_moved

If the destination is an existing directory, the source goes inside it:

mkdir d1 d2
touch d1/f
mv d1 d2
find d2

Output:

d2
d2/d1
d2/d1/f

Protecting Existing Files

mv also overwrites silently. It supports the same safety options as cp:

echo one > x1
echo two > x2
mv -n x1 x2
cat x2

Output:

mv: not replacing 'x2'
two

With -n, nothing moved, and a message explains why. The option -i asks first, and --backup=numbered keeps the old file under a numbered name before replacing it:

echo hi > dup
echo ho > dest/dup
mv --backup=numbered dup dest/
ls dest | grep dup

Output:

dup
dup.~1~

The file dest/dup is now the new one, and the previous version is saved as dup.~1~.

Reporting Errors

Both commands print a message and return a non-zero status when a source is missing:

mv nosuch.txt dest/
echo "status=$?"

Output:

mv: cannot stat 'nosuch.txt': No such file or directory
status=1

Practical Applications

Renaming Many Files at Once

mv renames one item per call, but a loop can call it repeatedly. This loop changes every .jpeg extension to .jpg:

touch img1.jpeg img2.jpeg img3.jpeg
for f in *.jpeg; do mv -- "$f" "${f%.jpeg}.jpg"; done
ls img*

Output:

img1.jpg  img2.jpg  img3.jpg

The expression ${f%.jpeg} removes the shortest match of .jpeg from the end of the value of f, and .jpg is then appended. The quotes around "$f" keep names with spaces together, and -- marks the end of options so that a name beginning with a dash is not mistaken for one.

Files With Spaces in Their Names

Quote the names, as with every command:

touch "my file.txt"
mv "my file.txt" "your file.txt"
ls "your file.txt"

Output:

your file.txt

Without quotes, mv my file.txt would receive the two names my and file.txt, and print mv: cannot stat 'my': No such file or directory.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Copying, Moving, and Renaming Files and get answers drawn from it.

Signed-in readers only.