Shell Script to Duplicate a file

Hi,

I want to duplicate a file in a folder. The file to be duplicated is named as a date like, “March 8, 2009.key”. The new file will have the name as a date a week later, like "March 15, 2099.key. I have an AppleScript that does this. But I want to use a shell script to see if it’s faster.

In the Terminal I can run this

cp “March 8, 2009.key” “March 15, 2009.key”

and get the desired results. But I can’t figure out how to do it using a shell script.

I thought something like this would work: (I put path of the file like, (Users:myname:Documents:folder:folder:filename) into the variable originalFile.

do shell script "/bin/cp " & quoted form of POSIX path of originalFile & space & (quoted form of POSIX path of originalFile)/newFileName

But it doesn’t.

Any help would be appreciated. Thanks.

Model: iMac
AppleScript: 2.0.1
Browser: Safari 525.27.1
Operating System: Mac OS X (10.5)

You almost have it.

do shell script "/bin/cp " & quoted form of POSIX path of originalFile & space & (quoted form of POSIX path of originalFile)/newFileName

For the destination, you have the full path of the original file plus the new file name. You want the path to the FOLDER containing the original file plus the new file name. Plus your quoted form of needs to include the file name. You current code gives a final destination path of:

‘Users:myname:Documents:folder:folder:filename’/newFIleName

You can use the Finder to get the path of the folder that contains a file:

tell application "Finder" to set PathToTheFile to (container of file originalFile) as string

Try this once you’ve added the above line:

do shell script "/bin/cp " & (quoted form of (POSIX path of originalFile)) & space & (quoted form of (POSIX path of (PathToTheFile & newFileName)))

Thank you very much Matt-Boy. That did it.

. or


do shell script "cd `dirname " & quoted form of POSIX path of originalFile & "`; cp " & originalfileName & space & newFileName

consider the `-characters, they are no single quotes

I ran into a little unexpected glitch. I was interested in testing the backtick method, to run the unix command inside it. It would fail if there were any spaces in the file path chosen. The path inside the backtick was quoted, but it seemed the result returned was no longer quoted. In the case of cd, it would just revert to the root (/). In other uses it might just error. What I found that worked was to add quotes (double). The following is just a test; it lets you pick a file, and returns the working directory:


set orig_file to choose file
do shell script "cd \"`dirname " & quoted form of POSIX path of orig_file & "`\"; pwd"