Skip to content

Instantly share code, notes, and snippets.

@acrodrig
Last active September 20, 2019 20:52
Show Gist options
  • Save acrodrig/a64834e40be898ef4a650f1977c3ffec to your computer and use it in GitHub Desktop.
Save acrodrig/a64834e40be898ef4a650f1977c3ffec to your computer and use it in GitHub Desktop.
# ----------------------------------------------------------------------------
# BASICS
# ----------------------------------------------------------------------------
# Colors - declare them to make it easier to use
COLOR_DEFAULT="\[\033[m\]"
COLOR_RED="\[\033[31m\]"
COLOR_GREEN="\[\033[32m\]"
COLOR_YELLOW="\[\033[33m\]"
COLOR_BLUE="\[\033[34m\]"
COLOR_PURPLE="\[\033[35m\]"
COLOR_CYAN="\[\033[36m\]"
COLOR_LIGHTGRAY="\[\033[37m\]"
COLOR_DARKGRAY="\[\033[1;30m\]"
COLOR_LIGHTRED="\[\033[1;31m\]"
COLOR_LIGHTGREEN="\[\033[1;32m\]"
COLOR_LIGHTYELLOW="\[\033[1;33m\]"
COLOR_LIGHTBLUE="\[\033[1;34m\]"
COLOR_LIGHTPURPLE="\[\033[1;35m\]"
COLOR_LIGHTCYAN="\[\033[1;36m\]"
COLOR_WHITE="\[\033[37m\]"
COLOR_BG_BLACK="\[\033[40m\]"
COLOR_BG_RED="\[\033[41m\]"
COLOR_BG_GREEN="\[\033[42m\]"
COLOR_BG_YELLOW="\[\033[43m\]"
COLOR_BG_BLUE="\[\033[44m\]"
COLOR_BG_PURPLE="\[\033[45m\]"
COLOR_BG_CYAN="\[\033[46m\]"
COLOR_BG_LIGHTGRAY="\[\033[47m\]"
# Simple Prompt as shown below with different colors for each concept
# <full-dir> (<git-branch>) $
git_branch() { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'; }
export PS1="$COLOR_CYAN\w$COLOR_YELLOW\$(git_branch)$COLOR_WHITE \$$COLOR_DEFAULT "
# History - ignore duplicates, and very long history (as to not forget)
export HISTCONTROL=ignoreboth:erasedups
export HISTSIZE=10000
# Append to the history file, don't overwrite it (see sensible bash at https://github.com/mrzool/bash-sensible)
shopt -s histappend
# Save multi-line commands as one command (see sensible bash at https://github.com/mrzool/bash-sensible)
shopt -s cmdhist
# Perform file completion in a case insensitive fashion (see sensible bash at https://github.com/mrzool/bash-sensible)
bind "set completion-ignore-case on"
# Display matches for ambiguous patterns at first tab press (see sensible bash at https://github.com/mrzool/bash-sensible)
bind "set show-all-if-ambiguous on"
# Include the coding spaces to navigate quickly to them
CDPATH=".:~:~/Dropbox/Code:~/Dropbox"
# Git (see https://github.com/git/git/blob/master/contrib/completion/git-completion.bash)
# source ~/.git-completion.bash
# Set autocomplete for AWS (see https://docs.aws.amazon.com/cli/latest/userguide/cli-command-completion.html)
complete -C '/usr/local/aws/bin/aws_completer' aws
# Load private variales (Mac OS X does not load `.bashrc` by default)
source ~/.bashrc
# ----------------------------------------------------------------------------
# ALIAS
# ----------------------------------------------------------------------------
# Git Aliases for quick use (inspited by http://mjk.space/git-aliases-i-cant-live-without/)
alias gb="git checkout"
alias gc="git commit -m"
alias gp="git push"
alias gr="git pull --rebase"
alias gs="git status"
# Color terminal when I ssh to other servers (see https://medium.com/@acrodriguez/changing-terminal-color-when-ssh-ing-to-a-server-20528a5df020)
alias ssh="/Users/andres/.ssh/color.sh"
# Alias to mysqldump
alias mysqldump="/usr/local/mysql/bin/mysqldump"
# ----------------------------------------------------------------------------
# UTILITIES
# ----------------------------------------------------------------------------
# search/hunt
# Small function(s) to search text in code from the command line without remembering grep options
# `search` searches all files and displays matching lines
# `hunt` searches all files and displays only the name of the file containing the match
function search() { grep --color -I --exclude-dir={node_modules,docs,_site,.git} -r "$1" *; }
function hunt() { grep -I -l --exclude-dir={node_modules,docs,_site,.git} -r "$1" *; }
# acp for "Add, Commit and Push"
function acp() {
git add --all .
git commit -m "${1:-Auto Commit and Push}"
git push
}
# fpd for "Fix Photo(s) Date(s)"
# Change dates based on EXIF creation date (works using Mac OS X utility `mdls` and `date`), can be invoked for a single
# file (fpd IMAGE.JSP) or all files in directory (fpd *)
function fpd() {
[ ! -f $1 ] && echo "usage: fpd <file1> <file2> ... <fileN>" && return 1
dc="\033[m"
wc="\033[37m"
for f in $@; do
udt=$(mdls $f | awk -F' *= *' '/kMDItemContentCreationDate / { print $2 }')
ldt=$(date -j -f "%Y-%m-%d %H:%M:%S %z" "$udt" "+%Y-%m-%d %H:%M:%S")
tdt=$(date -j -f "%Y-%m-%d %H:%M:%S %z" "$udt" "+%Y%m%d%H%M.%S")
echo -e Fixing $wc$f$dc date to $wc$ldt$dc
touch -cmt $tdt $f
done
}
# ips for "IP addresses on AWS"
# A function to fetch the IP addresses of all machines running on EC2 environment under a certain profile
# Notes:
# - To get IPs for multiple profiles: `ips prof1 prof2 ... profN`
# - You need `jq` (see https://stedolan.github.io/jq/ and https://remysharp.com/drafts/jq-recipes)
# - Uses AWS cli's `describe-instances` (see http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html)
# - Filtering `Name=instance-state-code,Values=16` returns only running instances
# - Filtering by path `.Reservations[].Instances[]` select all the instances in the reservation(s) objects
# - Filtering by path `( .Tags[] | select(.Key == "Name") | .Value )` select all tags, selects those with `Name` and returns value
# - The path `.PrivateIpAddress` select the private IP address
# - Finally `jq` puts them all in an array and outputs TSV
function ips() {
local profiles=${@:-"default"};
local aws_filter="Name=instance-state-code,Values=16"
local jq_filter=".Reservations[].Instances[] | [( .Tags[] | select(.Key == \"Name\") | .Value ), .PrivateIpAddress] | @tsv"
for p in $profiles; do
aws ec2 describe-instances --profile $p --filters "$aws_filter" | jq -r "$jq_filter" | sort
done
}
# vips for "Variables for IP addresses on AWS"
# Massages the output from `ips` and returs something that can be injected into a bash script
# If you want to have these variables available in the current terminal you can do:
# eval "$(vips prof1 prof2 ... profN)"
function vips() {
local profiles=${@:-"default"};
ips $profiles | sort | tr '[:lower:]' '[:upper:]' | tr '-' '_' | tr '\t' '=' | sed -e 's/=/_IP=/g'
}
# terms for "Terminals"
# Will open N other terminals for development
# https://superuser.com/questions/195633/applescript-to-open-a-new-terminal-window-in-current-space
# https://discourse.omnigroup.com/t/translate-applescript-example-to-javascript/13481/2
function terms() {
local cmd="terminal.doScript(\"printf '\\\\e[8;31;132t'\")"
local js="let terminal = Application(\"Terminal\"); $cmd; $cmd;"
osascript -l JavaScript -e "$js" > /dev/null
}
# medium for "Create Medium Post"
# See http://www.freblogg.com/2017/12/publish-articles-to-your-medium-blog-in_83.html
function medium() {
# Variable needs quotes to get evaluated (see https://unix.stackexchange.com/q/169020)
[ ! -f "$1" ] && echo "usage: medium <file-name>" && return 1
local host="https://api.medium.com/v1"
local auth="Authorization: Bearer $MEDIUM_PAT"
local dt=$([[ "$1" =~ ([0-9]{4}-[0-9]{2}-[0-9]{2}) ]] && echo ${BASH_REMATCH[1]})
# Get content, extract front matter, discover title
local content="$(jq -R -s . $1)"
local fm=$([[ "$content" =~ (---.+---) ]] && echo ${BASH_REMATCH[1]})
local title=$([[ "$fm" =~ title:[\s]*(.+)\\n ]] && echo ${BASH_REMATCH[1]} || echo ${1##*/})
content="# $title \\n\\n ${content:${#fm}+1:${#content}-${#fm}-2} \\n***\\n**Originally published at [R@andomCurve](http://www.randomcurve.com) on $dt**"
echo "Will post article '$title' to Medium ..."
# Get user ID and then post story
local user=$(curl -s -H "$auth" -H "Accept: application/json" -X GET $host/me | jq -r '.data.id')
local body='{ "title": "'$title'", "contentFormat": "markdown", "content": "'$content'", "publishStatus": "draft", "publishedAt": "'$dt'" }'
curl -H "$auth" -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d "$body" "$host/users/$user/posts"
}
# safe for "Safeguard local files"
function safe() {
local DIR="/Users/andres/Dropbox/Private"
# Copy important directories
cp -pR .config $DIR
cp -pR .ssh $DIR
# Copy files
cp -p .bash_history .bashrc .gitconfig .nanorc .profile $DIR
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment