Yes, use the -n switch, see cp(1).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.
In that case you'll have to script something around it. For example, ifI 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.
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.SirDice said:Yes, use the -n switch, see cp(1).
In that case you'll have to script something around it. For example, ifcp -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.
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
#!/bin/sh
filename="backup-`date "+%Y-%m-%d-%H%M%S"`"
echo $filename
wblock@ said:This is an ideal place for a shell script. A script can test to see if a file already exists:
Code: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:
Code:#!/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.