Skip to content

Instantly share code, notes, and snippets.

@fxchen
Created September 24, 2018 22:19
Show Gist options
  • Save fxchen/31e1e13c516a5cad7018bab2b4b34e3b to your computer and use it in GitHub Desktop.
Save fxchen/31e1e13c516a5cad7018bab2b4b34e3b to your computer and use it in GitHub Desktop.
Default zshrc config
# ~/zshrc
# 1. Run Install.sh (https://gist.github.com/fxchen/9c5c950b6c9117930fa2aff804e7856b)
# 2. Modify the bottom environment variables. Add a link to this zshrc from the profile
# 3. Set iTerm word jump https://coderwall.com/p/h6yfda/use-and-to-jump-forwards-backwards-words-in-iterm-2-on-os-x 5
# 4. Configure oh-my-zsh .zshrc: plugins=(git sublime osx git-flow git-extras npm node theme web-search battery)
# Inspiration: http://stevelosh.com/blog/2010/02/my-extravagant-zsh-prompt/
####################################################################
# Shell aliases
####################################################################
alias kf='kinit -f'
alias h='history'
history-search() { if [ -z "$*" ]; then history 1; else history 1 | egrep "$@"; fi; }
alias hs='history-search'
alias s="sudo"
alias c="clear"
alias ..='cd ..'
alias q='exit'
alias rm='rm -i'
alias c='clear'
alias f='find . -iname' # ex: f README\*
alias l="ls -hl"
alias la='ls -ahl'
alias lt='ls -ahlptr'
alias lsa='ls -a'
alias lsal='ls -al'
alias lsl='ls -l'
alias lstr='ls -ltr'
alias t='tail -200 '
alias tf='tail -f '
alias serve='python -mSimpleHTTPServer 8000 ./' # Serve a python server of the current directory at
alias pp='python -mjson.tool' # Pretty print python
alias pprint='pp'
alias untar='tar -xvzf'
alias tar-up='tar -cvzf '
alias path='echo -e ${PATH//:/\\n}' # Nicely print path
alias now='date +"%T"'
alias nowtime=now
alias nowdate='date +"%d-%m-%Y"'
alias ping='ping -c 5'
alias ports='netstat -tulanp'
alias header='curl -I'
alias recent_cmds='history | cut -c 8- | sort | uniq -c | sort'
alias kill_ds_store="find . -name '*.DS_Store' -type f -delete"
alias touchall='find . -name "*.rst" | xargs touch'
alias home="cd ~"
alias disk="cd /"
go-up () {
num=$1
for ((n=0; n<num; n++)); do cd ..; done
}
alias up='go-up'
####################################################################
# Tmux
####################################################################
tm() {
local attach window
if [ -n $1 ]; then
attach=""
tmux has-session -t $1 > /dev/null
if [ $? -eq 0 ]; then
attach=$1
shift
else
for session in `tmux ls|awk -F ":" '{ print $1 }'`;do
if [[ $session =~ ^$1 ]]; then
echo "Matched session: $session"
attach=$session
shift
break
fi
done
fi
if [[ $attach != "" ]]; then
if [ $# -eq 1 ]; then
for win in `tmux list-windows -t $attach|sed -E 's/^[0-9]+: //'|sed -E 's/[*-].*//'`;do
if [[ $win =~ ^$1 ]]; then
echo "Matched window: $window"
window=$win
break
fi
done
tmux -CC attach -t $attach:$window
else
tmux -CC attach -t $attach
fi
else
if [ $# -gt 1 ]; then
attach=$1
shift
tmux -CC new -s $attach -n $1
else
echo "Attempting to create $1"
tmux -CC new -s $1
fi
fi
else
tmux new
fi
}
alias tn='tmux -s' # New session
alias tl='tmux ls' # List sessions
alias ta='tmux -CC att -t' # Attach session <name>
#############################################################
# Git
#############################################################
# Git aliases
alias gl='git log '
alias glg='git lga'
alias gs='git status -sb'
alias ga='git add '
alias gaa='git add . '
alias gc='git commit '
alias gca='git commit --amend '
alias gcm='git commit -m '
alias gco='git checkout '
alias gr='git rebase '
alias grm='git rebase origin/master'
alias gpr='git pull --rebase '
alias gb='git checkout -b '
alias gf='git fetch '
alias gd='git diff '
alias gdc='git diff --cached '
alias gpo='git push origin'
# Most volatile / changed files
git-most-volatile-files-call () { git log --pretty=format: --name-only | sort | uniq -c | sort -rg | head -20; }
alias most-volatile-files='git-most-volatile-files-call'
alias git-most-volatile-files='git-most-volatile-files-call'
# Git: Recursing through directory
git-recursive-call () {
find . -name .git -type d | sort |
while read line; do
directory=`dirname $line`;
echo "$directory$";
(cd $directory && git "$@");
done
}
alias recursive='git-recursive-call'
alias git-recursive='git-recursive-call'
# Git: Rolling back
git-rollback-call(){
to=$1
git reset --soft HEAD~${to}
}
alias git-rollback='git-rollback-call'
alias rollback='git-rollback-call'
__sizeup_build_query () {
local bool="and"
local query=""
for t in $@; do
query="$query -$bool -iname \"*.$t\""
bool="or"
done
echo -n "$query"
}
__sizeup_humanize () {
local size=$1
if [ $size -ge 1073741824 ]; then
printf '%6.2f%s' $(echo "scale=2;$size/1073741824"| bc) G
elif [ $size -ge 1048576 ]; then
printf '%6.2f%s' $(echo "scale=2;$size/1048576"| bc) M
elif [ $size -ge 1024 ]; then
printf '%6.2f%s' $(echo "scale=2;$size/1024"| bc) K
else
printf '%6.2f%s' ${size} b
fi
}
sizeup-call () {
local helpstring="Show file sizes for all files with totals\n-r\treverse sort\n-[0-3]\tlimit depth (default 4 levels, 0=unlimited)\nAdditional arguments limit by file extension\n\nUsage: sizeup [-r[0123]] ext [,ext]"
local totalb=0
local size output reverse OPT
local depth="-maxdepth 4"
OPTIND=1
while getopts "hr0123" opt; do
case $opt in
r) reverse="-r " ;;
0) depth="" ;;
1) depth="-maxdepth 1" ;;
2) depth="-maxdepth 2" ;;
3) depth="-maxdepth 3" ;;
h) echo -e $helpstring; return;;
\?) echo "Invalid option: -$OPTARG" >&2; return 1;;
esac
done
shift $((OPTIND-1))
local cmd="find . -type f ${depth}$(__sizeup_build_query $@)"
local counter=0
while read -r file; do
counter=$(( $counter+1 ))
size=$(stat -f '%z' "$file")
totalb=$(( $totalb+$size ))
>&2 echo -ne $'\E[K\e[1;32m'"${counter}:"$'\e[1;31m'" $file "$'\e[0m'"("$'\e[1;31m'$size$'\e[0m'")"$'\r'
# >&2 echo -n "$(__sizeup_humanize $totalb): $file ($size)"
# >&2 echo -n $'\r'
output="${output}${file#*/}*$size*$(__sizeup_humanize $size)\n"
done < <(eval $cmd)
>&2 echo -ne $'\r\E[K\e[0m'
echo -e "$output"| sort -t '*' ${reverse}-nk 2 | cut -d '*' -f 1,3 | column -s '*' -t
echo $'\e[1;33;40m'"Total: "$'\e[1;32;40m'"$(__sizeup_humanize $totalb)"$'\e[1;33;40m'" in $counter files"$'\e[0m'
}
alias sizeup='sizeup-call'
#############################################################
# ZSH Set up
#############################################################
export UPDATE_ZSH_DAYS=45
HISTFILE=~/.zsh_history
HISTSIZE=999999999
SAVEHIST=$HISTSIZE
##################################################
#
# OhMyZsh prompts
#
##################################################
if [ "x$OH_MY_ZSH_HG" = "x" ]; then
OH_MY_ZSH_HG="hg"
fi
function virtualenv_info {
[ $VIRTUAL_ENV ] && echo '('`basename $VIRTUAL_ENV`') '
}
function hg_prompt_info {
# $OH_MY_ZSH_HG prompt --angle-brackets "\
# < on %{$fg[magenta]%}<branch>%{$reset_color%}>\
# < at %{$fg[yellow]%}<tags|%{$reset_color%}, %{$fg[yellow]%}>%{$reset_color%}>\
# %{$fg[green]%}<status|modified|unknown><update>%{$reset_color%}<
# patches: <patches|join( → )|pre_applied(%{$fg[yellow]%})|post_applied(%{$reset_color%})|pre_unapplied(%{$fg_bold[black]%})|post_unapplied(%{$reset_color%})>>" 2>/dev/null
}
function box_name {
[ -f ~/.box-name ] && cat ~/.box-name || hostname -s
}
ZSH_THEME_GIT_PROMPT_PREFIX=" on %{$fg[magenta]%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[green]%}!"
ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg[green]%}?"
ZSH_THEME_GIT_PROMPT_CLEAN=""
local return_status="%{$fg[red]%}%(?..✘)%{$reset_color%}"
RPROMPT='${return_status}%{$reset_color%}'
PROMPT='
%{$fg[magenta]%}%n%{$reset_color%}:%{$fg[yellow]%}$(box_name)%{$reset_color%}@%{$fg_bold[green]%}${PWD/#$HOME/~}%{$reset_color%}$(hg_prompt_info)$(git_prompt_info)
%{$fg[blue]%}%*%{$reset_color%}|%h$(virtualenv_info)> '
plugins=(git sublime osx git-flow git-extras npm node theme web-search battery)
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
# Terminal Title: ——> username@hostname (command): directory
case $TERM in
xterm*)
precmd () { print -Pn "\e]0;%n@%m: %~\a"}
preexec () { print -Pn "\e]0;%n@%m ($1): %~\a" }
;;
esac
##################################################
#
# ssh
#
##################################################
export SSH_KEY_PATH="~/.ssh/rsa_id"
export SSH_ENV=$HOME/.ssh/environment
set noclobber
limit coredumpsize unlimited
function start_agent {
echo "Initializing new SSH agent..."
/usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
echo succeeded
chmod 600 "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
/usr/bin/ssh-add
}
if [ -f "${SSH_ENV}" ]; then
. "${SSH_ENV}" > /dev/null
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
start_agent;
}
else
start_agent;
fi
##################################################
#
# Make zsh nicer
#
##################################################
# Changing Directories
unsetopt auto_cd # if I type a directory without 'cd', zsh automatically
# cds into it
setopt auto_pushd # when I cd, push the old directory onto the dir stack
setopt pushd_ignore_dups # don't push duplicate copies of a directory to
# the directory stack
# Completion
setopt auto_list # when tab completion is ambiguous, list choices
setopt auto_menu # when tab completion is ambiguous, use menu completion
# (fill in the next option when you press tab)
setopt list_beep # when tab completion is ambiguous, beep
unsetopt menu_complete # when tab completion is ambiguous, zsh automatically
# fills in the first option
unsetopt list_ambiguous # when there is an unambiguous prefix, insert that
# before inserting ambiguous stuff from the menu.
# menu_complete takes precedence over this.
# Expansion and Globbing
setopt glob # expand stuff to generate filenames.
setopt extended_glob # treat #, ~, and ^ as globbing patterns
setopt nomatch # zsh gets mad when I glob patterns that don't exist
# History
setopt append_history # append to the history file
setopt hist_ignore_dups # don't add immediately repeated commands to history
setopt extended_history # add timestamps to history. For a rough idea of the
# extra disk space this uses, you'll use up an extra
# 15kB for running 1000 commands. Your call.
# Init
# Input / Output
setopt aliases # use aliases defined below
setopt correct # correct my bad spelling of commands
unsetopt correct_all # correct my bad spelling of all argument son a line
# This is unset because it is fairly common to have an
# argument that is similar to a file in the current
# directory (eg, sudo git would correct to .git)
# CUSTOMIZE(keyboard_layout)
setopt print_exit_value # prints the exit value of commands when it's not 0
# (success); useful when writing shell scripts
# Job Control
setopt bg_nice # nice background jobs (run them with lower priority)
setopt check_jobs # yell at me if I try to exit zsh with jobs running
unsetopt notify # notify me of background job status immediately
# Prompting
# Scripts and Functions
setopt octal_zeroes # output octal numbers starting with a 0 instead of 8#
setopt c_bases # output hex numbers with 0x rather than 16#
setopt multios # allows redirection to multiple i/o streams; ie,
# echo "foo" > file1 > file2 | cat
# Completion
fignore=(.o .c~ .old .pro) # ignores these file types when doing file completion
# The same as the zstyle.
# Completion
fignore=(.o .c~ .old .pro) # ignores these file types when doing file completion
# The same as the zstyle.
alias mv='nocorrect mv' # no spelling correction on mv
alias cp='nocorrect cp' # no spelling correction on cp
alias mkdir='nocorrect mkdir' # no spelling correction on mkdir
alias lsd='ls -d *(-/DN)' # list directories
alias lsh='ls -ld .*' # list hidden
alias :q='exit' # quit out of the shell like from vim
alias :Q='exit'
alias off='sleep 0.5 && xset dpms force off'
# If messages are enabled with mesg y, then other people can message you using,
# for example, echo "Hey, Sam" | write samking would write "Hey, Sam" to my
# screen. This will work as a primitive chat feature. However, it also messes
# up your screen, so we disable it here.
mesg n
# umask says what permissions files have when they're created (ie, using touch
# or mkdir). If you use symbolic umask such as
# umask -S u=rw,g=r,o=r
# then you specify what IS allowed. In this example, the user can read and
# write, and group and other can read. Noone can execute.
# When you use octal notation such as
# umask 022
# then you specify what is not allowed. In this case, the group and others
# CANNOT write to newly created files by default.
# If you only want yourself to be able to do anything, you can
# umask 077
# to make it so that noone else has any permissions.
# Either way, your umask will mask against 666, which means that noone will
# have execute permission by default.
umask 022
# auto ls after cd
function cd() {
builtin cd "$*" && ls
}
# if vim is installed, we probably never want to use vi
if [ `command -v vim` ]; then
alias vi=vim
fi
################################################################################
# ZSTYLE OPTIONS
# These were generated by compinstall. They can be regenerated using
# compinstall, but that would destroy everything inside the "The following
# lines..." comment.
# They mostly involve expansion and completion.
# To see how to write your own completion functions (if they aren't built in),
# check out http://www.linux-mag.com/id/1106/
# Also, see man zshcompsys for more on compinit and completion generally
################################################################################
# The following lines were added by compinstall
zstyle ':completion:*' completer _expand _complete _ignored _match _correct _approximate _prefix
zstyle ':completion:*' completions 1
zstyle ':completion:*' glob 1
zstyle ':completion:*' list-colors ''
zstyle ':completion:*' matcher-list '+' '+m:{[:lower:]}={[:upper:]}' '+m:{[:lower:][:upper:]}={[:upper:][:lower:]}' '+r:|[._-]=* r:|=* l:|=*'
zstyle ':completion:*' max-errors 3 numeric
zstyle ':completion:*' menu select=long
zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s
zstyle ':completion:*' substitute 1
# insert all expansions for expand completer
zstyle ':completion:*:expand:*' tag-order all-expansions
# formatting and messages
zstyle ':completion:*' verbose yes
zstyle ':completion:*' group-name ''
zstyle ':completion:*:descriptions' format '%B%d%b'
zstyle ':completion:*:messages' format '%d'
zstyle ':completion:*:warnings' format 'No matches for: %d'
zstyle ':completion:*:corrections' format '%B%d (errors: %e)%b'
# offer indexes before parameters in subscripts
zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters
zstyle '*' hosts $hosts
zstyle '*' users $users
# Filename suffixes to ignore during completion (except after rm command)
zstyle ':completion:*:*:(^rm):*:*files' ignored-patterns '*?.o' '*?.c~' \
'*?.old' '*?.pro'
# ignore completion functions (until the _ignored completer)
zstyle ':completion:*:functions' ignored-patterns '_*'
# don't load every tab-completion module at startup. instead, mark them all
# as autoloaded so that when you need them, they'll get loaded.
autoload -Uz compinit
# allow tab completion for command line options
compinit
# End of lines added by compinstall
##################################################
#
# START mac shortcuts
#
##################################################
alias go_work='cd ~/Workspace'
alias go_dropbox='cd ~/Dropbox'
alias go_desktop='cd ~/Desktop'
alias go_downloads='cd ~/Downloads'
clear
FILE='/Users/fchen/Dropbox/notes/dalio-principles.txt'
head -$((${RANDOM} % `wc -l < $FILE` + 1)) $FILE | tail -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment