Sorry if I missed something in the cp manual, but is there a way to copy a file to a directory where there may be a file with the same name? Something like adding a postfix to the name of the copied file if there is a file with the same name on the destination directory. Something like:

ls foo
cp file foo/
ls foo

The OS, that I am running, is Ubuntu Gnu/Linux.

  • you want the postfix added if/when there's a file with the same name? – Jeff Schaller Feb 28 at 16:10
  • yes, like a star or anything. Edited – InfiniteLooper Feb 28 at 16:12
  • For there to be a good answer, I think you should settle on what you want :) – Jeff Schaller Feb 28 at 16:15
  • Also let us know whether you're on a Linux system or some other Unix. GNU cp has built-in support for backing existing files up (yes, that's not exactly what you want to do, but it's there). – Kusalananda Feb 28 at 16:21
  • Edited. Thanks for feedbacks as a new user of this Forum. Will read advices for newcommers :) – InfiniteLooper Feb 28 at 16:26

Adding a positive integer to the target name if the name is already taken, and also incrementing that integer until a free name is found:

mycp () {
    local source="$1"
    local target="$2"

    local n

    # If the target pathname is a directory, add the source filename
    # the end of it.
    if [ -d "$target" ]; then
        target+="/$(basename "$source")"

    # Increment n until a free name is found
    # (this may leave n unset if the source filename is free).
    while [ -e "$target$n" ]; do
        n=$(( n + 1 ))

    cp "$source" "$target$n"

Note: This function does not take any other arguments than a source and target pathname. It also assumes that you are using the bash shell.

To "install" it, just run the above code in your shell, or add it to wherever you usually add aliases and functions.


$ ls
dir file
$ ls dir/
$ mycp file dir
$ ls dir/
$ mycp file dir
$ ls dir/
file    file1
$ mycp file dir
$ ls dir/
file    file1   file2

You can roll your own function. This will keep adding underscores until there is not a duplicate:

mycp() {
    if [[ -f "$2" ]]; then
        mycp "$1" "${2}_"
        cp "$1" "$2"

Not compatible with passing arguments (e. g. cp -p). The better option is to use cp -n, which will not overwrite an existing file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.