How to cp file only if it does not exist, throw error otherwise?

user606521 picture user606521 · Nov 17, 2014 · Viewed 35.8k times · Source
aws s3 cp "dist/myfile" "s3://my-bucket/production/myfile"

It always copies myfile to s3 - I would like to copy file ONLY if it does no exist, throw error otherwise. How I can do it? Or at least how I can use awscli to check if file exists?

Answer

John Rotenstein picture John Rotenstein · Nov 18, 2014

You could test for the existence of a file by listing the file, and seeing whether it returns something. For example:

aws s3 ls s3://bucket/file.txt | wc -l

This would return a zero (no lines) if the file does not exist.


If you only want to copy a file if it does not exist, try the sync command, e.g.:

aws s3 sync . s3://bucket/ --exclude '*' --include 'file.txt'

This will synchronize the local file with the remote object, only copying it if it does not exist or if the local file is different to the remote object.