-
Notifications
You must be signed in to change notification settings - Fork 0
/
bash_aliases
492 lines (414 loc) · 14.9 KB
/
bash_aliases
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# Better diff (Mac only)
alias diff="colordiff --ignore-space-change -u"
# Datetime
alias today='date +%F'
alias now='date +%F_%H-%M-%S'
# Allow editing Mac crontab with Vim per:
# http://superuser.com/questions/359580/error-adding-cronjobs-in-mac-os-x-lion
alias crontab="VIM_CRONTAB=true crontab"
# ls conveniences
function ls() { # Display an empty line for empty directories
if [[ $(/bin/ls "${@}" | wc -l) -eq 0 ]]; then
echo
else
/bin/ls -G "$@"
fi
}
alias ll='ls -Alhtr'
alias llt='ll -t' # Sort by date last modified
alias la='ls -A'
alias l='ls'
# du should always be human readable
alias du='du -h'
# $1 - arguments to pass to ls
# $2 - function to use to sort ls results (head|tail)
# $3 - number of results to ask for from head/tail
function _ls_results {
ls "$1" | "$2" -n "$3"
}
# TODO Idea:
# "newest", "oldest", etc. can also take in a path to search for files on, perhaps? E.g. "newest 3 ~/Downloads*.par" says
# "Find the newest 3 files in ~/Downloads.par"
# Returns the __ most-recently-modified files
function newest {
if [[ $# -eq 0 ]]; then
NUM_RESULTS=1
else
NUM_RESULTS=$1
fi
_ls_results '-tr' 'tail' "$NUM_RESULTS"
}
alias latest="newest"
# Returns the __ least-recently-modified files
function oldest {
if [[ $# -eq 0 ]]; then
NUM_RESULTS=1
else
NUM_RESULTS=$1
fi
_ls_results '-tr' 'head' "$NUM_RESULTS"
}
alias earliest="oldest"
# Returns the __ first files alphabetically from ls
function first {
if [[ $# -eq 0 ]]; then
NUM_RESULTS=1
else
NUM_RESULTS=$1
fi
_ls_results '' 'head' "$NUM_RESULTS"
}
# Returns the __ last files alphabetically from ls
function last {
if [[ $# -eq 0 ]]; then
NUM_RESULTS=1
else
NUM_RESULTS=$1
fi
_ls_results '' 'tail' "$NUM_RESULTS"
}
# Returns the __ biggest files by filesize
function biggest {
if [[ $# -eq 0 ]]; then
NUM_RESULTS=1
else
NUM_RESULTS=$1
fi
_ls_results '-Sr' 'head' "$NUM_RESULTS"
}
# Returns the __ smallest files by filesize
function smallest {
if [[ $# -eq 0 ]]; then
NUM_RESULTS=1
else
NUM_RESULTS=$1
fi
_ls_results '-Sr' 'tail' "$NUM_RESULTS"
}
# Given a file, detects what type it is and:
# 1) cd's to it if it's a directory
# 2) opens it in Vim if it's a text file
# 3) throws an error if it's a binary file
function smart_open {
filepath="${1}"
if ! [ -e "${filepath}" ]; then
echo "Error: No such file at '${filepath}'" >&2
return 1
fi
filetype="$(file "${filepath}" | awk '{print $NF}')"
return_code=0
case "${filetype}" in
text)
vim "${filepath}"
;;
directory)
cd "${filepath}"
;;
*)
# TODO handle PDF & JPG types
echo "Error: Unknown filetype '${filetype}'" >&2
return_code=1
;;
esac
return "${return_code}"
}
# TODO Idea:
# Fuzzy_find and fuzzy_ls can take an additional argument of the directory to search!
# Make find not suck, and exclude some sensible defaults (which I hope don't come back to bite me one day...)
alias cif="find . ! -name '*.class' -and -iname" # Case-insensitive find
function fuzzy_find() {
ARGS="${@}"
cif "*${ARGS// /*}*"
}
function fuzzy_ls() {
ARGS="${@}"
cif "*${ARGS// /*}*" -maxdepth 1
}
alias ff="fuzzy_find"
alias fl="fuzzy_ls"
# Overwrite cd to jump up multiple levels with 'cd <# dir>..' syntax
function cd() {
# If string isn't long enough, use builtin cd anyways
if [[ ${#1} -lt 3 ]]; then
builtin cd "$@"
else
# Check if string is in '<number>..' form
if [[ "${1:(-2)}" == ".." ]] && [[ -n "${1%..}" ]] && [[ "${1%..}" =~ ^[0-9]+$ ]]; then
REPEAT_TIMES="${1%..}"
if [ "${REPEAT_TIMES}" -le 0 ]; then
echo "Cannot do ${REPEAT_TIMES} cd's"
return 1
fi
CD_STR=""
while read; do
CD_STR="../$CD_STR"
done < <(seq 1 "${REPEAT_TIMES}")
cd "$CD_STR"
else
builtin cd "$@"
fi
fi
}
# Allows user to choose which lines of piped input to pass through
alias filter="~/.bash_utils/filter.py"
alias ft="filter"
# Pipes the output of the given command to filter
function _pipe_to_filter() {
"${@}" | filter
}
alias flf="_pipe_to_filter fuzzy_ls"
alias fff="_pipe_to_filter fuzzy_find"
# TODO Idea:
# Store a history of fuzzy find + filter searches,
# and remember the choices the user makes so we
# can give them a default choice the next time
# Fuzzy searches for the given file, then filters output and feeds it into the given command
# $1 - Command to feed chosen file to
# $2 - Command to generate results for filtering
# $3+ - Arguments passed to command for generating results to filter
function use_command_filter_results() {
# Unquoted word-splitting is intentional here
${1} $(${2} "${@:3}" | filter)
}
alias vff="use_command_filter_results 'vim -O' fuzzy_find"
alias vfl="use_command_filter_results 'vim -O' fuzzy_ls"
# Easily copy the contents of one or more file
function clip() {
pbcopy < "${@}"
}
# Have mkdir create parent directories if they don't already exist
alias mkdir="mkdir -p"
# === grep ===========
alias csgr='grep -I --color=auto' # Case-sensitive grep
alias gr='csgr -i'
alias csegr='grep -I --color=auto' # Case-sensitive egrep
alias egr='csegr -i'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
function rgr() { gr --exclude-dir="." --exclude-dir=".." -r "$@" ./* ./.*; }
function csrgr() { csgr --exclude-dir="." --exclude-dir=".." -r "$@" ./* ./.*; } # Case-sensitive recursive grep
function ergr() { egr --exclude-dir="." --exclude-dir=".." -r "$@" ./* ./.*; }
function csergr() { csegr --exclude-dir="." --exclude-dir=".." -r "$@" ./* ./.*; } # Case-sensitive recursive egrep
# Grep chain commands
alias hgr='history | gr'
alias pgr='ps aux | gr'
# Map command to open last vim session
alias v="vim"
# TODO I have never used this and maybe I never will
VIM_SESSION=~/.vim/.saved-session.vim
alias vims="vim -S ${VIM_SESSION}"
# Jobs should show PID by default
alias jobs="jobs -l"
# Don't want to make srm too easy to use!
# alias srm="srm -i"
# Output redirection functions
# TODO These don't seem to work so well..
function unify_output() { 2>&1 "${@}"; }
function quiet() { "${@}" 2> /dev/null; }
function silent() { "${@}" > /dev/null 2>&1; }
# Easy SSH port forwarding
function sshl {
COMMAND="${@:2}"
ssh -L "${1}:localhost:${1}" "${COMMAND[@]}"
}
# Command line JSON prettifier
alias prettify-json="python -mjson.tool"
# Just because it's intuitive
alias eject="diskutil unmount"
alias chrome="open -a 'Google Chrome'"
alias sp="vim -o"
alias vsp="vim -O"
# Handy convenience function for opening a meeting notes file from template
function meeting() {
if [[ "${#}" -lt 3 ]]; then
echo -e "Usage:\tmeeting <note destination dir> <template filepath> <note name fragment> [<note name fragment>...]"
return 1
fi
dest_dirpath="${1}"
shift
template_filepath="${1}"
shift
args_str="${@}"
filename="${args_str// /-}"
filepath="${dest_dirpath}/$(today)_${filename%%.md}.md"
if ! [[ -f "${filepath}" ]]; then
vim -c "read ${template_filepath}" "${filepath}"
else
vim "${filepath}"
fi
}
# Convenience method for starting a new set of meeting notes for a project
# NOTE: This relies on the meeting_notes_template_filepath variable being set
function easy_meeting() {
if [ -z "${meeting_notes_template_filepath}" ]; then
echo "meeting_notes_template_filepath variable is unset; make sure it gets set in ~/.bash_local" >&2
return 1
fi
project="${1}"
meeting_notes_dirpath="${HOME}/Documents/${project,,}/meeting-notes"
if ! [ -d "${meeting_notes_dirpath}" ]; then
mkdir "${meeting_notes_dirpath}"
fi
meeting "${meeting_notes_dirpath}" "${meeting_notes_template_filepath}" "${@}"
}
# Convenience method for converting meeting notes to Markdown
function easy_chrome() {
project="${1}"
shift 1
meeting_notes_dirpath="${HOME}/Documents/${project,,}/meeting-notes"
(
cd "${meeting_notes_dirpath}"
# Interestingly, piping to 'readarray' doesn't work, but this does
readarray -t matching_files < <(fuzzy_ls "${@}" | filter)
if ! [ ${#matching_files[@]} -eq 0 ]; then
chrome "${matching_files[@]}"
fi
)
}
# ======================================================================================
# Git
# ======================================================================================
# Viewing changes
alias gs="git status -sb"
alias gsh="git show"
alias gd="git diff --word-diff=color"
alias gdc="gd --cached"
alias gl="git log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(bold black)[%an]%C(reset)%C(bold yellow)%d%C(reset)' --all"
# Making changes
alias gb="git branch"
alias gco="git checkout"
alias ga="git add"
# We hijack Git's autocomplete here so we get autocompletion on our custom aliases
# This relies on the bash-completion Homebrew package
__git_complete gco _git_checkout
__git_complete gb _git_branch
# TODO It's getting to the point where I need a better system for dealing with fuzzy find/ls results..
alias gaff="use_command_filter_results 'git add' fuzzy_find"
alias gafl="use_command_filter_results 'git add' fuzzy_ls"
alias empty-commit="git commit --allow-empty -m $1"
alias gcm="git commit"
alias gcmm="git commit -m $1"
alias gg="git commit -am $1"
alias grs="git reset"
alias grs1="git reset --soft HEAD^"
# Dealing with remotes
alias gcl="git clone"
alias gf="git fetch --prune"
alias gpll="git pull"
function gpsh() { # Push the branch upstream if it doesn't exist; otherwise just git push
BRANCH_NAME="$(git rev-parse --abbrev-ref HEAD)"
if [[ $(git config "branch.$BRANCH_NAME.merge") == '' ]]; then
git push -u origin "$BRANCH_NAME" "$@"
else
git push "$@"
fi
}
alias gprune-local-dry-run="git branch --merged | grep -v '\*' | grep -v 'master' | grep -v 'develop'"
alias gprune-local="git branch --merged | grep -v '\*' | grep -v 'master' | grep -v 'develop' | xargs -n 1 git branch -d"
alias gfl="bash ~/.bash_utils/gitflow-pp.sh"
# ======================================================================================
# Gradle
# ======================================================================================
# Searches for a gradlew file up the tree and uses it for gradle commands
# Add 'nocd' as the first argument to run the gradle commands from the directory you're in at the moment
function gradle_search() {
ORIG_DIR="$PWD"
while [[ "$PWD" != "/" ]]; do
if [[ -f "./gradlew" ]]; then
if [[ "$1" == "nocd" ]]; then
GRADLE_DIR=$(pwd)
cd "$ORIG_DIR"
echo "$GRADLE_DIR"/gradlew "${@:2}"
"$GRADLE_DIR"/gradlew "${@:2}"
else
./gradlew --daemon "$@"
cd "$ORIG_DIR"
fi
return 0
else
cd ..
fi
done
cd "${ORIG_DIR}"
echo "No gradlew file found in any parent directories" >&2
}
alias grd="gradle_search"
alias rsync="rsync --perms --progress"
# Easy SSH aliases
# Interesting tidbit: I used to have a 'for line in $(grep '^Host.....)' thing here, but
# one of my HostName entries in my SSH config file was '*', which was getting Bash glob-expanded and causing problems!
# Lesson learned...
grep '^Host' "${HOME}/.ssh/config" | grep -v '[*]' | awk '{print $2}' | while read -r ssh_host; do
alias "${ssh_host}"="ssh '${ssh_host}'"
done
alias virtualenv="pyenv virtualenv"
# Make following a file much easier
alias lsf="less +F"
# Call this script and pass a text file with a list of servers. You will ssh to the servers as the current user.
# Once connected use Ctrl + a to enter commands
# de/syncronize panes = Ctrl + a + s
# Change panes = Ctrl + a + arrow-keys
# Zoom into pane = Ctrl + a + z
function parallel-tmux() {
tmux new-session -s $(date +"%F_%H-%M-%S") -d
count=-1
for i in $(cat $1); do
let count=${count}+1
if [ $count -eq 0 ]; then
tmux new-window "ssh $i"
else
tmux split-window -h "ssh $i"
tmux select-layout tiled
fi
done
tmux set-window-option synchronize-panes on
tmux attach
}
# ======================================================================================
# Navigation
# ======================================================================================
function _smart_open_dir_file {
cd "${2}"
if [ "${#}" -gt 2 ]; then
use_command_filter_results 'smart_open' "${1}" "${@:3}"
fi
}
dotfiles_dirpath="${HOME}/app/dotfiles"
alias dotfiles="cd '${dotfiles_dirpath}'"
code_dirpath="${HOME}/code"
alias code="_smart_open_dir_file fuzzy_ls '${code_dirpath}'"
downloads_dirpath="${HOME}/Downloads"
alias downloads="_smart_open_dir_file fuzzy_ls '${downloads_dirpath}'"
gdrive_dirpath="${HOME}/gdrive"
alias gdrive="_smart_open_dir_file fuzzy_ls '${gdrive_dirpath}'"
check_dirpath="${gdrive_dirpath}/checklists-and-templates"
alias check="_smart_open_dir_file fuzzy_find '${check_dirpath}'"
gref_dirpath="${gdrive_dirpath}/general-reference"
alias gref="_smart_open_dir_file fuzzy_ls '${gref_dirpath}'"
receipts_dirpath="${gdrive_dirpath}/receipts-records-confirmations"
alias receipts="_smart_open_dir_file fuzzy_find '${receipts_dirpath}'"
psup_dirpath="${gdrive_dirpath}/project-support"
alias psup="_smart_open_dir_file fuzzy_ls '${psup_dirpath}'"
someday_dirpath="${gdrive_dirpath}/someday-maybe"
alias someday="_smart_open_dir_file fuzzy_find '${someday_dirpath}'"
alias self_improvement="_smart_open_dir_file fuzzy_find '${gref_dirpath}/self-improvement'"
# ======================================================================================
# Docker
# ======================================================================================
clear_containers() {
docker rm $(docker stop $(docker ps -a --quiet --format="{{.ID}}"))
}
alias cclear=clear_containers
clear_old_images() {
docker image rm $(docker images --quiet --filter "dangling=true")
}
alias iclear=clear_old_images
# ======================================================================================
# Custom-Built Apps
# ======================================================================================
# Wealthdraft aliases
alias wealthdraft="java -jar ${HOME}/app/wealthdraft/*.jar"
# cli-journal aliases
alias journal="java -jar ${HOME}/app/cli-journal/*.jar"
alias jnew="journal new"
alias todays-goals="journal new todays-goals.md todays-goals"