Skip to content

Instantly share code, notes, and snippets.

@i-like-robots
Last active October 1, 2019 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save i-like-robots/7f2168bbbdc105b4b9113d5f9ad24b8e to your computer and use it in GitHub Desktop.
Save i-like-robots/7f2168bbbdc105b4b9113d5f9ad24b8e to your computer and use it in GitHub Desktop.
Upload client-side assets to S3 via AWS CLI
#!/bin/bash
SOURCE_FILES=($(find public/*.{js,css,gz,br,map} 2>/dev/null))
DESTINATION_BUCKET="hashed-assets-eu"
DESTINATION_FOLDER="page-kit"
for FILE in ${SOURCE_FILES[@]}; do
if [[ $FILE == *".gz" ]]; then
ENCODING="gzip"
elif [[ $FILE == *".br" ]]; then
ENCODING="br"
fi
# the AWS CLI can guess content types but not the original type of compressed files
# <https://github.com/aws/aws-cli/issues/3817>
case $FILE in
*".js"|*".js.gz"|*".js.br")
TYPE="application/javascript"
;;
*".css"|*".css.gz"|*".css.br")
TYPE="text/css"
;;
*".map")
TYPE="application/octet-stream"
;;
esac
aws s3 cp $FILE "s3://$DESTINATION_BUCKET/$DESTINATION_FOLDER/$FILE" \
--cache-control=31536000 \
--content-type="$TYPE; charset=utf-8" \
--content-encoding="$ENCODING" \
--acl="public-read"
done
@CLTPayne
Copy link

Question - with variables like $FILE - is it a thing that's it's safer for them to be wrapped in ""? I vaguely remember being told this was 'safer' and Bats throwing an error if not "$VAR" but can't find a convincing explanation as to why in this particular case. https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable

@apaleslimghost
Copy link

if it's not quoted, and the filename contains spaces, then bash will expand it to multiple arguments to the command you're passing the variable to, which we probably don't want

@apaleslimghost
Copy link

i've forked the gist to add appropriate quoting and wrapped things in functions for proper local variable scoping https://gist.github.com/quarterto/4e8bbb7391455d15dbe40be74150dcd3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment