Skip to content

Instantly share code, notes, and snippets.

@kljensen
Last active May 28, 2020 12:30
Show Gist options
  • Save kljensen/f7dc8e9dcd256cad28d22c4acf30a63c to your computer and use it in GitHub Desktop.
Save kljensen/f7dc8e9dcd256cad28d22c4acf30a63c to your computer and use it in GitHub Desktop.
#!/usr/bin/env zsh
# This is a zsh shell script for uploading files to s3 in order to share
# them via email, sms, or similar. The uploaded files are purged from your
# s3 bucket after 30 days so that you don't incur storage costs. After upload
# the public URLs for your files are copied to the clipboard (if you're using
# a mac and have `pbcopy`). The only zsh-specific part of the code is the
# array append/join (I think). You can likely port this to a different shell
# with relative ease. This requires the AWS CLI, AWS credentials (`aws configure`),
# and an existing bucket (see `$BUCKET` below).
# Run like `share foo-bar.png baz-woot.png`
share () {
BUCKET="my-bucket-name"
slugify () {
echo $1 | iconv -t ascii//TRANSLIT | sed -E 's/[^a-zA-Z0-9]+/-/g' | sed -E 's/^-+|-+$//g' | tr A-Z a-z
}
initialize () {
# Create the bucket
aws s3 mb s3://$BUCKET >/dev/null
FILENAME=$(mktemp)
cat <<EOF >"$FILENAME"
{
"Rules": [
{
"Expiration": {
"Days": 30
},
"ID": "30d expiration",
"Filter": {
"Prefix": "30d/"
},
"Status": "Enabled",
"NoncurrentVersionExpiration": {
"NoncurrentDays": 30
},
"AbortIncompleteMultipartUpload": {
"DaysAfterInitiation": 1
}
},
{
"Expiration": {
"Days": 7
},
"ID": "7d expiration",
"Filter": {
"Prefix": "7d/"
},
"Status": "Enabled",
"NoncurrentVersionExpiration": {
"NoncurrentDays": 7
},
"AbortIncompleteMultipartUpload": {
"DaysAfterInitiation": 1
}
}
]
}
EOF
# Set expiration rules
aws s3api put-bucket-lifecycle-configuration --bucket $BUCKET --lifecycle-configuration file://$FILENAME
rm $FILENAME
}
#
# See if we're going to initialze the bucket
for arg in "$@"
do
case $arg in
-i|--initialize)
initialize
return
;;
esac
done
output=()
upload () {
CLEAN=`slugify $1`
aws s3 cp $1 s3://$BUCKET/30d/$CLEAN --acl public-read >/dev/null
output+=("https://s3.amazonaws.com/$BUCKET/30d/$CLEAN")
}
for var in "$@"
do
upload "$var"
done
printf "%s\n" "${output[@]}" | tee >(pbcopy)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment