# Using CP to make differential copies



## adripillo (Jun 7, 2013)

Can I use the command cp or another copy command or some script maybe to copy a file to a folder but with the option to not replace. I mean I have bk.tgz, can cp or other command copy the file and auto set to rename it in case if the file exist?. Like bk.tgz bk2.tgz and so on.


----------



## SirDice (Jun 7, 2013)

adripillo said:
			
		

> Can I use the command cp or another copy command or some script maybe to copy a file to a folder but with the option to not replace.


Yes, use the -n switch, see cp(1).



> I mean I have bk.tgz, can cp or other command copy the file and auto set to rename it in case if the file exist? Like bk.tgz bk2.tgz and so on.


In that case you'll have to script something around it. For example, if `cp -n somefile /some/place/$name` returns anything but 0 you could loop back, update the $name variable and try again until it succeeds. Should be relatively easy to script.


----------



## adripillo (Jun 7, 2013)

SirDice said:
			
		

> Yes, use the -n switch, see cp(1).
> 
> 
> In that case you'll have to script something around it. For example, if `cp -n somefile /some/place/$name` returns anything but 0 you could loop back, update the $name variable and try again until it succeeds. Should be relatively easy to script.



I already tried -n but It only tells me when file is the same or not, if it is the same it does not copy and if it is not the same it replace.

I hope someone could help with that script because that is not my fort, my knowledge on scripting is very low and basic. Thanks for reply.


----------



## wblock@ (Jun 7, 2013)

This is an ideal place for a shell script.  A script can test to see if a file already exists:

```
if [ -f "$targetfilename" ]; then
  # file already exists, add "-dup" to name of new file
  # although that duplicate might exist, too...
  targetfilename="$targetfilename-dup"
  cp "$sourcefilename" "$targetfilename"
fi
```

If this is for backups, a better solution is generating the filename from the date and time:

```
#!/bin/sh
filename="backup-`date "+%Y-%m-%d-%H%M%S"`"
echo $filename
```

As long as backups take more than one second, the filenames will be unique.  They are also self-documenting.


----------



## adripillo (Jun 7, 2013)

wblock@ said:
			
		

> This is an ideal place for a shell script.  A script can test to see if a file already exists:
> 
> ```
> if [ -f "$targetfilename" ]; then
> ...



Thanks a lot. Let me "play" with this a little, I will let you know how it ends.


----------



## adripillo (Jun 7, 2013)

Ok, It worked fine. All solved for the moment. Thanks!!


----------

