-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell_aliasrc
488 lines (398 loc) · 16 KB
/
shell_aliasrc
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
# ----- Start in the last directory you were in ------------------------------
# Move to the last saved working directory if one exists
if [ -e ~/.last_cd ]
then
cd "$(cat ~/.last_cd)"
fi
# Saves current directory between sessions
unalias cd 2>/dev/null # Prevent infinite loops if sourcing this file again in the same session
logged_cd() {
cd "$@"
pwd > ~/.last_cd
}
alias "cd"="logged_cd" # keep track of most recent directory
alias "cdb"="cd ~-" # cd to previous directory
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias ..2="cd ../.."
alias ..3="cd ../../.."
alias ..4="cd ../../../.."
alias ..5="cd ../../../../.."
alias cd..="cd .."
alias cd...="cd ../.."
alias cd....="cd ../../.."
alias cd.....="cd ../../../.."
alias cd......="cd ../../../../.."
alias md="mkdir"
alias rg="rg -S" # Makes ripgrep case insensitive by default (use rg -s for case sensitive)
alias rgf="rg --files | rg" # For searching through only filenames in current dir instead of file contents
alias df="duf" # A better df alternative
alias du="dust -d 1" # A better du alternative - shows the sizes of all subdirs in this current dir
alias gpsh="git push"
alias gpl="git pull"
# Make a dir and immediately cd into it
function mkdircd(){
mkdir "$1" && cd "$1"
}
alias mkdirc="mkdircd"
alias mkcd="mkdircd"
tmux_clear() {
if [ -n "$TMUX" ]; then
clear
tmux clear-history
else
clear
fi
}
alias "clear"="tmux_clear"
# Use vim keybindings in the terminal!
#set -o vi
# ----- convenient alias and function definitions ----------------------------
# ls uses colors, shows human-readable file sizes, shows indicators to classify file types
# Assuming that you are using gnu core utils installed via brew
# Otherwise, you need to uncomment the below lines to enable the different,
# Mac-specific ls flags to enable colors
alias ls='ls --color=auto --human-readable --classify'
#if [[ ${OS_NAME} == "Linux" ]]; then
#alias ls='ls --color=auto --human-readable --classify'
#elif [[ ${OS_NAME} == "Mac" ]]; then
#alias ls='ls -G -h -F'
#fi
alias l='ls'
alias la='ls -Al'
alias lla='la'
alias lal='la'
alias ll='ls -l'
alias llt='ls -lt'
alias llth='ls -lt | head' # get the few most recently modified files
alias lltr='ls -ltr'
alias lltrh='ls -ltr | head'
alias l.="ls -A | egrep '^\.'" # List only hidden files
alias sl='ls'
alias grep='grep --color=auto'
alias lgrep="ls -AF | grep"
diff-pretty() {
if which diff-so-fancy >/dev/null; then
diff -u $1 $2 | diff-so-fancy
else
diff -u $1 $2
fi
}
alias diff='diff-pretty'
alias killz='killall -9 '
alias hidden='ls -a | grep "^\..*"'
# Use \command to run the unaliased version of any command
# such as if you want to rm a large dir without it printing everything, use \rm
alias rm='rm -v'
alias cp='cp -v'
alias mv='mv -v'
alias shell='ps -p $$ -o comm='
alias cc='gcc -Wall -W -ansi -pedantic -O2 '
alias valgrind-leak='valgrind --leak-check=full --show-reachable=yes'
alias g='git'
alias gi='git'
alias v='vim'
alias nv='nvim'
alias s='source'
alias pdb='python -m pdb'
alias jup='jupyter'
alias jupnb='jupyter notebook'
# Open github url for current repo's remote
alias gh_open="git remote -v | awk '/fetch/{print \$2}' | sed -Ee 's#(git@|git://)#https://#' -e 's@com:@com/@' | head -n1 | xargs open"
# Connect to existing tmux session if one exists, else create a new one
tm() {
num_sess=$(tmux list-session | wc -l)
if [[ ${num_sess} -gt 1 && $# -ne 1 ]]; then
echo "ERR: There are multiple tmux sessions, so call this function with an argument choosing the session number"
echo "$(tmux list-session)"
return 1
elif [[ ${num_sess} -gt 1 && $# -eq 1 ]]; then
tmux attach -t $1
elif [[ ${num_sess} -eq 1 ]]; then
tmux attach # Connect to existing session
else
tmux # Make new session
fi
}
# Attach to a session. Ex. "tmls" and then "tma projX" where projX is one of the names shown in tmls
# To make a named session do "tmux new -s <proj_name>"
alias tma="tmux attach -t"
alias tmls='tmux ls'
# Python venv utils
# Create a venv with `python -m venv <venv_name>`. Most commonly do `python -m venv venv`
# Deactivate the current venv with simply the command `deactivate`
VA() {
venv_folder_name="${1:-venv}" # Uses the name 'venv' by default since that's most common
source "${venv_folder_name}/bin/activate"
}
# Usage: CA <venv>
alias CA='conda activate'
alias CD='conda deactivate'
alias capt="CA pytorch_p36"
alias CAPT="CA pytorch_p36"
alias catf="CA tensorflow_p36"
alias CATF="CA tensorflow_p36"
alias tb='tensorboard --logdir'
alias ai="aichat"
alias aic="aichat -c" # ai code
alias aiq="aichat" # ai question
# fzf + autojump
# Like normal autojump when used with arguments, but displays an fzf prompt when used without
j() {
if [[ "$#" -ne 0 ]]; then
cd $(autojump $@)
return
fi
cd "$(autojump -s | sort -k1gr | awk '$1 ~ /[0-9]:/ && $2 ~ /^\// { for (i=2; i<=NF; i++) { print $(i) } }' | fzf --height 40% --reverse --inline-info)"
}
# Set up fzf key bindings and fuzzy completion
eval "$(fzf --zsh)"
# fzf + $PATH
# Search for things in your $PATH
# list directories in $PATH, press [enter] on an entry to list the executables inside.
# press [escape] or ctrl-C to go back to directory listing
fzfpath() {
local loc=$(echo $PATH | sed -e $'s/:/\\\n/g' | eval "fzf ${FZF_DEFAULT_OPTS} --header='[find:path]'")
if [[ -d $loc ]]; then
echo "$(rg --files $loc | rev | cut -d"/" -f1 | rev)" | eval "fzf ${FZF_DEFAULT_OPTS} --header='[find:exe] => ${loc}' >/dev/null"
fzfpath
fi
}
### fzf + brew
# Search for a brew package and then install it!
fzfbrew() {
local inst=$(brew search | eval "fzf ${FZF_DEFAULT_OPTS} -m --header='[brew:install]'")
if [[ $inst ]]; then
for prog in $(echo $inst); do
brew install $prog
done
fi
}
# Make fzf use ripgrep by default
# Main benefit of this is so that fzf will ignore files in .gitignore by default
# which is great
if type rg &> /dev/null; then
export FZF_DEFAULT_COMMAND='rg --files --hidden'
fi
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
# Make ctrl-k in terminal auto-open fzf history window
# This is really good since you might know that the cmd you want is 2 up
# arrows away normally, but this lets you *visually* see that which is
# just very nice
# bindkey "$terminfo[kcuu1]" fzf-history-widget
bindkey "^k" fzf-history-widget
# Default ctrl-L just scrolls down instead of actually clearing the past terminal lines
# This makes it clear everything
clear-terminal() { tput reset; zle redisplay; }
zle -N clear-terminal
bindkey '^L' clear-terminal
# This function does an adb logcat and only shows you the logs printed from your specific app's PID
# Call this function with the package name of your app: e.g. com.converge.com
# Note that once the app crashes or ends, you'll have to re-run this command since the app will have a new PID
function adb_logcat_myapp() {
if [[ $# -ne 1 ]]; then
echo -e "\nErr: Call this with your app package name (e.g. com.company.app)"
echo -e "\nRun \`adb shell ps | less\` to find your package name if you don't know it"
adb shell ps | head
else
adb logcat | grep `adb shell ps | grep $1 | tr -s '[:space:]' ' ' | cut -d' ' -f2`
fi
}
alias logcat-app=adb_logcat_myapp
# Shows the 10 most recently modifed files from most recent descending
find_recent_modified_files() {
if [[ -z $1 ]]; then
IGNORE_HIDDEN_FILES=false
elif [[ $1 == "--ignore-hidden" ]]; then
IGNORE_HIDDEN_FILES=true
else
echo "Invalid argument. Supported options are: '--ignore-hidden'."
return 1
fi
if [[ ${OS_NAME} == "Mac" ]]; then
if [[ ${IGNORE_HIDDEN_FILES} == "true" ]]; then
find . -not -path '*/\.*' -exec stat -f '%m%t%Sm %N' {} + | sort -nr | cut -f2- | head -n10
else
find . -exec stat -f '%m%t%Sm %N' {} + | sort -nr | cut -f2- | head -n10
fi
elif [[ ${OS_NAME} == "Linux" ]]; then
if [[ ${IGNORE_HIDDEN_FILES} == "true" ]]; then
find . -type f -not -path '*/\.*' -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head
else
find . -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head
fi
fi
}
alias mods="find_recent_modified_files"
# Find files that are modified n minutes ago, where n is the argument
# Ex. lastmod 5 # Lists all files modified within the past 5 minutes
function lastmod() {
find -type f -mmin -$1 -exec ls -l {} +
}
# List the largest files in this directory (shows in bytes)
alias largest-files="find . -printf '%s %p\n' | sort -rn | head"
# List the largest directories and files in this dir (shows in MB)
alias largest-dirs="\du -am | sort -rn | less"
# List the largest immediate directories in this dir (shows in MB)
alias largest-dirs-1="\du -m --max-depth 1 | sort -rn | head"
# Displays top processes by memory usage
alias largest-mem="ps -eo size,pid,user,command --sort -size | awk '{ hr=\$1/1024 ; printf(\"%13.2f Mb \",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf(\"%s \",\$x) } print \"\" }' | head -n 15"
# Aliases thefuck pkg as 'tf' so just type that to fix a command
eval $(thefuck --alias tf)
# Call from cmdline as 'aws_profile <prof_name>' to switch the current aws cli profile
# Profile names are found in ~/.aws/config
function aws-profile() {
if [[ $# -eq 0 ]]; then
echo -e "\nErr: Call this with a profile name"
echo -e "Your profiles (~/.aws/config):\n"
cat ~/.aws/config
else
export AWS_PROFILE=$1
fi
}
# AWS CLI utility functions
function hostname_from_instance() {
aws ec2 describe-instances --filters "{\"Name\":\"tag:Name\", \"Values\":[\"$1\"]}" --query='Reservations[0].Instances[0].PublicDnsName' --output text | tr -d '"'
}
function ip_from_instance() {
name="$1"
shift # Remove name from args list
aws ec2 describe-instances --filters "{\"Name\":\"tag:Name\", \"Values\":[\"$name\"]}" --query='Reservations[0].Instances[0].PublicIpAddress' "$@" --output text | tr -d '"'
}
# Call as 'ssh-aws <name>' with ' --region <reg-name>' if default region not set in aws-cli
# Region can be anything like us-west-2 (don't put any sub-region letters since it won't work)
# TODO: Figure out how to pass ssh options like -Y and -L 6006:localhost:6006
function ssh-aws() {
ssh "ubuntu@$(ip_from_instance "$@")"
if [[ $? == 255 ]]; then
echo "If the machine name could not be resolved, verify that your aws cli profile is set to the correct user"
return 255
fi
}
# TODO: Figure out how a scp function from an ec2 name would be possible
# Maybe just parse for the string before a colon to find the name, and check that there is only one colon in the passed args
function scp-aws() {
orig_cmd="$*"
# Count NumFields with colons
num_colons=$(echo "$orig_cmd" | awk -F: '{print NF-1}')
if [[ $num_colons != 1 ]]; then
echo "ERR: You must only have 1 colon in this scp command. Found: $num_colons."
return 1
fi
echo "|$orig_cmd|"
# TODO: region extraction doesn't work.
region=$(echo "$orig_cmd" | sed -E 's@^(.).*\s--region\s([\w,-]*).*$@\1\2@')
#region=$(echo "$orig_cmd" | sed -E 's@^(.*\s|)(.*)(:.*$)@\1\2@')
echo "r:$region"
return 1
# Extract word before the colon
name_match_str='^(.*\s|)(.*)(:.*$)'
name=$(echo "$orig_cmd" | sed -E 's/'"$name_match_str"'/\2/')
echo "$name"
ip=$(ip_from_instance "$name")
echo "$ip"
ip="43433"
final_cmd=$(echo "$orig_cmd" | sed -E 's/'"$name_match_str"'/scp \1'"$ip"'\3/')
echo "$final_cmd"
}
# Report port forwarding functions from https://superuser.com/questions/248389/list-open-ssh-tunnels/1437366#1437366
function ports_local_forwardings() {
echo
echo "LOCAL PORT FORWARDING"
echo
echo "You set up the following local port forwardings:"
echo
lsof -a -i4 -P -c '/^ssh$/' -u$USER -s TCP:LISTEN
echo
echo "The processes that set up these forwardings are:"
echo
# -a ands the selection criteria (default is or)
# -i4 limits to ipv4 internet files
# -P inhibits the conversion of port numbers to port names
# -c /regex/ limits to commands matching the regex
# -u$USER limits to processes owned by $USER
# http://man7.org/linux/man-pages/man8/lsof.8.html
# https://stackoverflow.com/q/34032299
ps -f -p $(lsof -t -a -i4 -P -c '/^ssh$/' -u$USER -s TCP:LISTEN)
}
function ports_remote_forwardings() {
echo
echo "REMOTE PORT FORWARDING"
echo
echo "You set up the following remote port forwardings:"
echo
ps -f -p $(lsof -t -a -i -c '/^ssh$/' -u$USER -s TCP:ESTABLISHED) | awk '
NR == 1 || /R [[:digit:]]+:\S+:[[:digit:]]+.*/
'
}
#### Better grep that excludes directories from the .gitignore file in the current repo
function grep_ignore() {
if [ -r .gitignore ]; then
while read -r line; do
if [[ "$line" =~ '#' ]] || [[ "$line" =~ ^$ ]]; then
continue
fi
EXCLUDE="$EXCLUDE --exclude-dir=\"$line\""
done < .gitignore
fi
# Recursive, Display line number of match in file, Ignore case
eval grep -rni "$EXCLUDE" '"$@"'
}
alias grepignore='grep_ignore'
export PATH="$PATH:$HOME/.rvm/bin"
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
function add_domain_to_blacklist() {
if [[ $# -eq 0 ]]; then
echo "ERR: Call this with a domain name"
return 1
fi
# Need to sudo the entire thing since just doing 'sudo echo...' doesn't work because the shell is the one doing the redirection '>>' not the echo command
sudo sh -c "echo '127.0.0.1 $1' >> /etc/hosts"
}
alias blacklist_domain='add_domain_to_blacklist'
function find-all-hidden-swp-files() {
find . -type f -name ".*.swp"
}
function delete-all-hidden-swp-files() {
echo "\nDeleting files\n"
while IFS= read -r file_to_delete; do
rm -f "${file_to_delete}"
done < <(find-all-hidden-swp-files)
}
alias rm-all-hidden-swp-files='delete-all-hidden-swp-files'
# Displays the content of all *untracked* files in the current git repo, from the current dir down
# Can combine running this with `less` as `show-all-untracked-file-contents | less` to get in a paged format
function show-all-untracked-file-contents() {
git ls-files --others --exclude-standard | while read file; do echo -e "\n\n\n\n\n\n=============\033[32m\n$file"; echo -e "\033[0m"; cat "$file"; done
}
alias cat-untracked-file-contents='show-all-untracked-file-contents'
# Enables having the `pbpaste | something | pbcopy` idiom as `pbfilter something`, which enables easy filtering/transformation of clipboard text through a shell command
# Ex.
# - pbfilter | json_pp
# - pbfilter | sed 's/this/that/'
# - pbfilter | vipe # to edit text more easily in vim and then save it back to clipboard
# Calling this without arguments will remove any formatting from the text in the pasteboard, putting just plain text back.
# It does have a some limitations, though: you can't use it with an alias, or pipeline, or anything complex like that. The filter command must be a single regular command (or function) and its arguments.
function pbfilter() {
if [ $# -gt 0 ]; then
(pbpaste | "$@" | pbcopy)
else
pbpaste | pbcopy
fi
}
# Can't use vipe with pbfilter as vipe is interactive, so this separate one just for vipe
function pbvipe() {
pbpaste | vipe | pbcopy
}
function pb_python_dict_to_json() {
pbpaste | python -c "import json; import sys; import ast; string = sys.stdin.read(); d = ast.literal_eval(string); out = json.dumps(d); print(out)" | pbcopy
}
# ----- local configuration ----------------------------------------------------
# Put settings that should be there for each local machine in ~/.shellrc.extra
# so that local preferences aren't pushed to the git repo
if [[ -f ~/.shellrc.extra ]]; then
source ~/.shellrc.extra
fi
# Put all scripts in this folder into the PATH so that they can be called from anywhere in the shell
export PATH=~"/.scripts_global:$PATH"