Skip to content
shellhacks.dev
Command Line

Copy without overwriting

Copy without overwriting an existing file with cp -n. In GNU coreutils 9.1 it skips the copy and still exits 0, a status that later releases changed.

1 min read
Summarize in AI

A copy should leave files in the destination alone when they are already there, so a rerun cannot destroy changes.

Shell
mkdir -p src dst
echo new > src/a.txt
echo keep > dst/a.txt
cp -n src/a.txt dst/
echo "exit status: $?"
cat dst/a.txt
Text
exit status: 0
keep

-n is --no-clobber in GNU cp. The existing file wins and the command reports success, so a repeated run cannot overwrite local edits. The alternative, -i, stops to ask, which does not suit a script.

The exit status of a skipped copy has changed between coreutils releases, and the status of 0 shown here is from coreutils 9.1 on Debian 12, so check the release notes of the version you deploy before testing $? in a script. For a guarantee of what was copied, rsync --ignore-existing is the clearer tool.

Share

More snippets

Command Line

List hidden files only

List hidden files only with ls -d .[!.]* in GNU coreutils 9 or any POSIX shell. The glob skips the dot and double dot entries that .* would match.

1 min read
Command Line

Show the full timestamp of files

Show the full timestamp of every file with ls -l --full-time in GNU coreutils. It prints nanosecond precision and the zone, which ls -l hides.

1 min read
Command Line

Count the files in a directory

Count the files in a directory with ls -A | wc -l, or with find when names may contain newlines. A plain ls -1 skips every hidden file.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.