Amazon Cyber Monday deals See deals →ad

Mets Minor League Blog

Music theory, instruments and musicians

Mets Minor League Blog

Music theory, instruments and musicians

Linux Copy File If Exists: Safe Commands and Options

Yes. On Linux, cp SOURCE DESTINATION copies a file when the source exists; if the destination already exists, cp normally replaces its contents. To copy only when the destination is absent, use a shell test such as [ ! -e DESTINATION ] && cp SOURCE DESTINATION, or GNU cp -n for a no-clobber copy.

What “if exists” can mean

The phrase can describe two different checks, and choosing the right one prevents accidental data loss:

  • Copy if the source exists: cp source.txt backup/ succeeds when source.txt exists and is readable. If it does not, cp reports an error and returns a nonzero status.
  • Copy if the destination does not exist: Use a no-clobber option or test the destination first. This avoids replacing an existing file.
  • Copy only if both exist: Check both paths in a shell condition before running cp. This is useful in scripts where a missing input should be handled deliberately.

In ordinary interactive use, the first meaning is often enough: cp already checks that its source can be opened. The second meaning matters when preserving an existing destination is important.

Basic cp behavior

The standard command-line form is cp [OPTION] SOURCE DESTINATION. For example, cp report.txt archive/report.txt copies the source to that exact destination path. If the destination names an existing regular file, the default behavior is to overwrite it. If the destination is an existing directory, cp report.txt archive/ puts a copy named report.txt inside it.

To copy a file only when its source exists, you can simply run cp and check the result. In a script, an explicit test can make the intended behavior clearer:

if [ -f "$source" ]; then
    cp -- "$source" "$destination"
else
    printf 'Source file not found: %s\n' "$source" >&2
    exit 1
fi

Here, -f checks that the path is a regular file. Use -e instead if directories and other existing filesystem objects should also count. Quoting variables protects paths containing spaces, and -- marks the end of options so a filename beginning with a hyphen is not interpreted as a flag. These conventions apply to GNU coreutils cp and are widely supported, though option details can vary on non-GNU systems.

Copy without replacing an existing file

GNU cp -n means “no clobber”: it does not overwrite an existing destination. For example:

cp -n -- source.txt destination.txt

This is concise, but the exact reporting behavior when the destination already exists can depend on the implementation and version. Do not assume a particular exit status means that a copy occurred; check the relevant system’s cp documentation if a script relies on that distinction.

A portable shell-style alternative is to test first:

if [ ! -e "$destination" ]; then
    cp -- "$source" "$destination"
fi

This expresses the rule directly, but it has an important limitation: another process could create the destination after the test and before cp opens it. That gap is a race condition. For ordinary personal scripts, the test may be sufficient; for concurrent or security-sensitive operations, prefer an approach that creates the destination atomically or use application-specific locking. A check followed by a copy is not, by itself, a guarantee that no file will be replaced.

Choose options for the job

Several cp options help control what happens during a copy:

  • -i asks before overwriting an existing destination. It is useful at a terminal, but an automated script may wait for input or behave unexpectedly if no terminal is available.
  • -n skips existing destinations on GNU systems and other implementations that support it.
  • -f requests removal of an existing destination before copying when needed. It is not a “copy only if the source exists” option, and it can make replacement more forceful.
  • -v prints the paths as files are copied, which helps confirm what happened.
  • -p preserves common file attributes such as mode, ownership where permitted, and timestamps; -a is commonly used to archive trees while preserving more metadata and symlinks.

For example, to copy a file while asking before replacement, use cp -i -- source.txt destination.txt. To copy a directory tree, use a recursive or archive option, such as cp -a -- source_dir/ backup/. Be aware that copying a directory into an existing directory can create a nested directory rather than replace the existing tree. Check the source and destination paths carefully before running recursive commands.

Directories, wildcards, and common errors

To copy all matching text files, a shell pattern can be used: cp -- *.txt backup/. The shell expands *.txt before cp runs. If there are no matches, what happens depends on the shell configuration: commonly the pattern remains literal, causing an error, while some shells can be configured to treat an unmatched pattern differently. A loop with an explicit file check may be more predictable in a script.

Other frequent problems include:

  • Wrong destination type: A destination directory must exist unless you create it first with mkdir -p backup.
  • Permission denied: The user needs permission to read the source and to create or modify files in the destination directory. Running as root should not be the first fix; inspect ownership and permissions.
  • Same file: Copying a file onto itself produces an error rather than a useful copy.
  • Dangling symbolic link: A path can name a symlink whose target is missing. Tests such as -e generally follow symlinks, so they may report that the target does not exist even though the link itself is present.

Use printf '%s\n' "$path" or quote paths in commands to avoid surprises from spaces and special characters. For destructive or bulk operations, first try a representative command on a test directory and inspect the result.

cp compared with install and rsync

cp is the straightforward choice for a one-off local copy. The install command can copy a file and set its permissions or ownership as part of deployment, for example install -m 0644 source.conf /etc/example.conf; it is not a general substitute for every copy workflow. rsync is useful for synchronizing directories, transferring data over a network, and copying only changes, but its options and destination rules deserve careful review before use.

None of these commands automatically gives a complete backup strategy. A copy on the same disk may be lost with the original disk, and a later overwrite can destroy the only earlier version. If preserving prior contents matters, create a versioned backup or use a backup system rather than relying only on a no-clobber flag.

Frequently Asked Questions

Does Linux cp copy only if the source file exists?
Yes. cp must open the source, so it copies when the source is available and reports an error if the source is missing or inaccessible.

How do I copy a file only if the destination does not exist?
On GNU systems, use cp -n -- source destination. For a shell condition, use [ ! -e "$destination" ] && cp -- "$source" "$destination", keeping in mind that the check and copy are not atomic.

Does cp overwrite files by default?
Yes. When the destination is an existing regular file, the usual default is to replace its contents. Use -i to prompt or a supported no-clobber option to avoid overwriting.

What does cp -u do?
-u is an update option: it generally copies when the source is newer than the destination or when the destination is missing. It is not the same as “copy only if the destination does not exist,” because it can update an older existing file.

How can I tell whether cp succeeded?
Check its exit status. In a shell script, if cp -- "$source" "$destination"; then ... runs the success branch only when the command reports success. Use -v for visible copy output, but do not treat printed output alone as a substitute for checking errors.

Linux Copy File If Exists: Safe Commands and Options
Scroll to top