Skip to content

Instantly share code, notes, and snippets.

@adrienne
Created January 5, 2012 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrienne/1567276 to your computer and use it in GitHub Desktop.
Save adrienne/1567276 to your computer and use it in GitHub Desktop.
Use cURL to get a remote file into an editor (originally from here: https://github.com/cowboy/dotfiles/blob/master/bin/curlmate)
#!/bin/bash
if [[ ! "$1" || "$1" == "-h" || "$1" == "--help" ]]; then cat <<HELP
Curl a remote file into an editor.
http://benalman.com/
echo "Usage: $(basename "$0") [curloptions...] url"
Curl a remote file into the editor of your choice. The filename will be based
on the URL's filename. If a file extension can't be determined from the URL,
index.html will be used.
The editor will be auto-magically determined by stripping any leading "curl"
off this script's filename. For example, call this script "curlmate" and "mate"
will be run.
Copyright (c) 2011 "Cowboy" Ben Alman
Licensed under the MIT license.
http://benalman.com/about/license/
HELP
exit; fi
script="$(basename "$0")"
bin="${script#curl}"
cache_dir=~/.dotfiles/caches/"$script"
# Create tempfile.
tmp="$(mktemp "/tmp/$script.XXXXX")"
# Curl (using all specified options) to tempfile, storing url for later.
echo -e 'Fetching file...\n'
url="$(curl "$@" -o "$tmp" -w '%{url_effective}')"
# Remove leading http:// or https:// from url, and add index.html at the end if
# filename can't be determined.
path="$(echo "$url" | perl -pe's#^https?://##i;s#/$|(^[^/\s]+|/[^/.\s]+)$#$1/index.html#')"
dir="$cache_dir/$(dirname "$path")"
file="$dir/$(basename "$path")"
# Create directory if it doesn't exist.
[ -e "$dir" ] || mkdir -p "$dir"
# Copy tempfile to final file.
mv "$tmp" "$file"
# Open file in editor!
echo -e "\nOpening ~${file#$HOME}"
"$bin" "$file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment