As others have already noticed, there are two problems with your approach. They have nothing to do with .zip
vs .sh
files, but with the names and locations of the files.
You need to put double quotes around command substitution. Otherwise they break at space characters. See Why does my shell script choke on whitespace or other special characters? for more details.
Furthermore the ls
command outputs just the base name of the file, without the directory part. cp
therefore only sees the base name and has no idea that you meant files in a different directory. One way to fix this is to switch to the desired directory first.
cd /Users/Me/Documents/Coffi\ Work/FTP\ Backup\ Shell\ Script/Original/
cp -p -- "`ls -tr | tail -n1`" ../Backup1/
If you want just the latest zip file and not the latest file whatever it is:
cd /Users/Me/Documents/Coffi\ Work/FTP\ Backup\ Shell\ Script/Original/
cp -p -- "`ls -dtr -- *.zip | tail -n1`" ../Backup1/
This will fail with a strange error message if the directory is empty or if there is a file name containing newlines or characters that are not printable in the current locale but these are relatively rare circumstances.
The option -d
is a bit of additional safety in case there is a subdirectory whose name matches *.zip
. You don't need the option -1
, its effect is automatic when the output of ls
is redirected to another command.
Alternatively, you can use zsh which makes this nice and easy thanks to its glob qualifiers.
cp -p /Users/Me/Documents/Coffi\ Work/FTP\ Backup\ Shell\ Script/Original/*(om[1]) /Users/Me/Documents/Coffi\ Work/FTP\ Backup\ Shell\ Script/Backup1/
ls
will not return absolute path..you need to run the command from source directory.. – heemayl Apr 09 '15 at 14:36/Users/Me/Documents/Coffi\ Work/FTP\ Backup\ Shell\ Script/Original/
it works. How can I fix this? – smj2393 Apr 09 '15 at 14:42