-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path.bash_alias
More file actions
505 lines (438 loc) · 17.4 KB
/
.bash_alias
File metadata and controls
505 lines (438 loc) · 17.4 KB
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
493
494
495
496
497
498
499
500
501
502
503
504
505
function weather() {
if [[ -z $1 ]]; then
curl wttr.in/$1
elif [[ -z $CITY ]]; then
curl wttr.in/$CITY
else
echo "Please specify city!"
fi
}
function find_big_files() {
find . -size +"$1" -type f -print0 | xargs -0 ls -Ssh | sort -z
}
# Find file functions
# https://github.com/adsr/dotfiles/blob/master/bashrc
function ff() { local IFS='*'; local patt="$*"; find . -iwholename "*${patt}*"; }
function fo() { ff "$@" | head -n1; }
function fd() { local IFS='*'; local patt="$*"; find . -type d -iname "*${patt}*"; }
function fcd() { local d=$(fd "$@" | head -n1); [ -n "$d" ] && cd "$d"; }
# Emulate the "pbcopy" and "pbpaste" commands from Mac OS X
if ! [ -x "$(command -v xclip)" ]; then
sudo apt install -y xclip
fi
alias pbcopy='xclip -selection clipboard'
alias pbpaste='xclip -selection clipboard -o'
# Extract common archive files by file extension
function extract() {
if [ -f $1 ] ; then
case $1 in
*.tar.gz|*.tgz) tar xzf $1 ;;
*.tar|*.tar.xz) tar xf $1 ;;
*.tar.bz2|*.tbz2) tar xjf $1 ;;
*.xz) unxz $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.tar.zst) tar -I=unzstd xf $1 ;;
*.zst) unzstd $1 ;;
*.7z) 7z x $1 ;;
esac
else
echo "'$1' is not valid archive file."
fi
}
# Colorize output of man command
# http://tuxdiary.com/2016/06/16/color-man-pages/#more-27324
# https://hunden.linuxkompis.se/2021/02/17/coloured-manual-pages.html
function man() {
env \
LESS_TERMCAP_mb=$'\e[01;31m' \
LESS_TERMCAP_md=$'\e[01;31m' \
LESS_TERMCAP_me=$'\e[0m' \
LESS_TERMCAP_se=$'\e[0m' \
LESS_TERMCAP_so=$'\e[01;44;33m' \
LESS_TERMCAP_ue=$'\e[0m' \
LESS_TERMCAP_us=$'\e[01;32m' \
man "$@"
}
# Create a directory and change to it
function mcd() {
mkdir -pv $1
cd $1
}
# Use xdg-open in a subshell, derived output and detached
function open() {
(nohup xdg-open "$1" >/dev/null 2>&1 &)
}
# Get latest statistics for COVID-19 in USA
function coronavirus_cases() {
curl -s https://corona-stats.online/GT?minimal=true | head -n 3 | awk '{ print $2 $3 "\t"$5 "\t"$6 "\t" $7 "\t" $8 $9 "\t" $10 $11 }'
}
# Generate a random alphanumeric password
function genpass() {
local passlen=${1:-32} # Default length is 32 characters
LC_ALL=C tr -cd '[:alnum:]' < /dev/urandom | fold -w $passlen | head -n1
}
# Display headers from a web site/URL (requires cURL)
function headers() {
curl -sv "$@" 2>&1 >/dev/null |
grep -v "^\*" |
grep -v "^}" |
cut -c3-
}
# Simple command-line calculator
function = {
# declare -i i=${1:-$(</dev/stdin)};
# echo "$i" | bc -l
scale=${SCALE:-6} # Use $SCALE or default of 6 digits of precision
echo "scale=$scale; $@" | bc -l
}
alias calc="="
# Get public IP address
function whats-my-ip() {
ip=`curl --silent https://httpbin.org/ip | jq -r .origin`
echo $ip | xclip -selection clipboard
notify-send -t 5000 "$ip copied to clipboard."
}
function dirsize() {
sudo du -cxh -d 1 . | sort -h;
}
# Go up the specified number of directory levels (e.g., "up 4")
function up() {
local d=""
limit=$1
for ((i=1 ; i <= limit ; i++))
do
d="$d"/..
done
d=$(echo $d | sed 's/^\///')
if [[ -z "$d" ]]; then
d=..
fi
cd "$d"
}
# Colorize tail output for log files based on type of message on line
# https://github.com/cgoldberg/dotfiles/blob/master/.bash_aliases#L548
function ctail() {
tail -f -n 80 "$1" |
sed --unbuffered \
-e 's/\(.*FATAL.*\)/\o033[31m\1\o033[39m/' \
-e 's/\(.*ERROR.*\)/\o033[31m\1\o033[39m/' \
-e 's/\(.*WARN.*\)/\o033[33m\1\o033[39m/' \
-e 's/\(.*INFO.*\)/\o033[32m\1\o033[39m/' \
-e 's/\(.*DEBUG.*\)/\o033[34m\1\o033[39m/' \
-e 's/\(.*TRACE.*\)/\o033[30m\1\o033[39m/' \
-e 's/\(.*[Ee]xception.*\)/\o033[39m\1\o033[39m/'
}
# Search command history by regex (case-insensitive) and show last n matches
# usage: hs <pattern>
# https://github.com/cgoldberg/dotfiles/blob/master/.bash_aliases#L271
function hs() {
local n="150"
history | grep -i --color=always "$1" | tail -n "$n"
}
# Convert input string to all only lowercase alphanumeric characters separated with hyphens
# https://github.com/SixArm/sixarm-unix-shell-functions
function slugify() {
printf %s\\n "$*" | sed 's/[^[:alnum:]]/_/g; s/--*/-/; s/^-*//; s/-*$//;' | tr '[[:upper:]]' '[[:lower:]]'
}
# Convert input string to all only alphanumeric characters separated with underscores
# https://github.com/SixArm/sixarm-unix-shell-functions
function snake_format() {
printf %s\\n "$*" | sed 's/[^[:alnum:]]\{1,\}/_/g; s/_\{2,\}/_/g; s/^_\{1,\}//; s/_\{1,\}$//;'
}
# List files in current directory and sub-directories displayed as a tree
# https://github.com/SixArm/sixarm_unix_shell_scripts/blob/main/ls-tree
function lstree() {
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
}
# Convert between JSON and YAML
# http://github.com/frgomes/bash-scripts
function json2yaml {
python -c 'import sys, yaml, json; print(yaml.dump(json.loads(sys.stdin.read())))'
}
function yaml2json {
python -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin.read())))'
}
# Print display of terminal foreground and background colors with legend.
# https://github.com/mathaou/dotfiles/blob/master/.bashrc
function colors() {
local fgc bgc vals seq0
printf "Color escapes are %s\n" '\e[${value};...;${value}m'
printf "Values 30..37 are \e[33mforeground colors\e[m\n"
printf "Values 40..47 are \e[43mbackground colors\e[m\n"
printf "Value 1 gives a \e[1mbold-faced look\e[m\n\n"
# foreground colors
for fgc in {30..37}; do
# background colors
for bgc in {40..47}; do
fgc=${fgc#37} # white
bgc=${bgc#40} # black
vals="${fgc:+$fgc;}${bgc}"
vals=${vals%%;}
seq0="${vals:+\e[${vals}m}"
printf " %-9s" "${seq0:-(default)}"
printf " ${seq0}TEXT\e[m"
printf " \e[${vals:+${vals+$vals;}}1mBOLD\e[m"
done
echo; echo
done
}
# Experimental command-line search engine
# Example: rip "q=software testing"
# alias rip="curl -G -H 'Accept: text/plain' --url https://dontbeevil.rip/search --data-urlencode "
#alias ls='ls --group-directories-first --time-style=+"%m/%d/%Y %H:%M" --color=auto -F'
#alias ll='ls -lrt --group-directories-first --time-style=+"%m/%d/%Y %H:%M" --color=auto -F'
#alias la='ls -la --group-directories-first --time-style=+"%m/%d/%Y %H:%M" --color=auto -F'
# octal file modes through http://stackoverflow.com/questions/1795976/can-the-unix-list-command-ls-output-numerical-chmod-permissions
#alias lsoct='ls -al --color=auto|awk '\''{k=0;s=0;for(i=0;i<=8;i++){;k+=((substr($1,i+2,1)~/[rwxst]/)*2^(8-i));};j=4;for(i=4;i<=10;i+=3){;s+=((substr($1,i,1)~/[stST]/)*j);j/=2;};if(k){;printf("%0o%0o ",s,k);};print;}'\'''
# System functions
# https://www.digitalocean.com/community/tutorials/an-introduction-to-useful-bash-aliases-and-functions
alias df="df -Tha --total"
alias du="du -ach | sort -h"
alias pl="ps -eH -o user,pid,ppid,pgid,%cpu,%mem,vsz,rss,tty,stat,etime,args | less -S" # process list
alias path='printf "%b\n" "${PATH//:/\\n}"' # Pretty print $PATH
alias rm='rm -i -v'
alias cp='cp -v'
alias mv='mv -v'
alias mkdir='mkdir -pv'
alias top='htop'
alias apt-version='apt-cache madison'
alias more='less'
# Copy public and private SSH keys to clipboard
alias pubkey="more ~/.ssh/id_ed25519.pub | pbcopy | echo ' => Public key copied to clipboard.'"
alias prikey="more ~/.ssh/id_ed25519 | pbcopy | echo ' => Private key copied to clipboard.'"
# Colorize output of ip command
alias ip='ip -c'
# Get public IP address
alias publicip='curl https://ipecho.net/plain; echo'
# Another method to get public IP using 'dig'
alias ext_ip="dig +short myip.opendns.com @resolver1.opendns.com"
# Get local IP address
# https://github.com/jpbruinsslot/dotfiles/blob/master/files/alias/.alias
alias localip="sudo ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'"
# Show WiFi access points
alias wifi_ap="nmcli dev wifi list"
# View HTTP traffic
# https://github.com/lacymorrow/dotfiles/blob/master/.aliases
alias sniff="sudo ngrep -d 'eth0' -t '^(GET|POST) ' 'tcp and port 80'"
alias httpdump="sudo tcpdump -i eth0 -n -s 0 -w - | grep -a -o -E \"Host\: .*|GET \/.*\""
# Searchable 'ps' command alias
alias psg="ps aux | grep -v grep | grep -i -e VSZ -e"
# Summary of top 10 commands from history
alias hist_summary='history | awk '\''{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}'\'' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10'
alias hist_summary2="history | awk {'print $2, $3, $4'} | sort | uniq -c | sort -k1 -rn | head -n 30"
alias dateiso='date -u +"%Y-%m-%dT%H:%M:%SZ"'
# Run nano with sudo using current user's .nanorc.
alias snano="sudo nano --rcfile=~/.nanorc "
# Git aliases
alias gitlog='git log --all --decorate --graph --oneline'
alias glog="git log --graph --pretty=format:'%Cred%h%Creset %an: %s - %Creset %C(yellow)%d%Creset %Cgreen(%cr)%Creset' --abbrev-commit --date=relative"
# Undo last commit, but don't throw away your changes.
alias git-undo="git reset --soft HEAD^"
# Run Docker GUI application in container.
# Specify the Docker container name on command line.
# Ensure that 'xhost' has been run prior to enable permissions to X11 display.
alias d-run="docker run --rm -it --net=host --cpuset-cpus 0 --memory 512mb -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY "
# Open a random 'man' page - Great way to learn new commands
alias randman="apropos . | shuf -n 1 | awk '{print$1}' | xargs man"
# Display information about Linux distribution, package management, etc.
alias distinfo="echo /etc/*_ver* /etc/*-rel*; cat /etc/*_ver* /etc/*-rel*"
# URL-encode strings
alias urlencode='python2 -c "import sys, urllib as ul; print ul.quote_plus(sys.argv[1]);"'
# Set some helpful defaults for nano
alias nano='nano --smarthome --multibuffer --const --autoindent --suspend --linenumbers'
# APT (Auto Package Tool) aliases
alias apt-clean="sudo apt autoremove -f && sudo apt autoclean && sudo apt clean"
# Functionalize 'command -v' to allow 'if get_command [command]' idiom
# https://github.com/rawiriblundell/dotfiles/blob/master/.bashrc
get_command() {
local errcount cmd
case "${1}" in
(-v|--verbose)
shift 1
errcount=0
for cmd in "${@}"; do
command -v "${cmd}" ||
{ printf -- '%s\n' "${cmd} not found"; (( errcount++ )); }
done
(( errcount == 0 )) && return 0
;;
('')
printf -- '%s\n' "get_command [-v|--verbose] list of commands" \
"get_command will emit return code 1 if any listed command is not found" >&2
return 0
;;
(*)
errcount=0
for cmd in "${@}"; do
command -v "${1}" >/dev/null 2>&1 || (( errcount++ ))
done
(( errcount == 0 )) && return 0
;;
esac
# If we get to this point, we've failed
return 1
}
alias exists="get_command"
alias is_command="get_command"
# Always run these commands with 'sudo'
for cmd in apt-get apt-cache update-grub shutdown reboot ; do
alias $cmd="sudo $cmd"
done; unset cmd
# Use Neovim for Vim, if available
[ -x "$(command -v nvim)" ] && alias vim="nvim" vimdiff="nvim -d"
# `tre` is a shorthand for `tree` with hidden files and color enabled, ignoring
# the `.git` directory, listing directories first. The output gets piped into
# `less` with options to preserve color and line numbers, unless the output is
# small enough for one screen.
function tre() {
tree -aC -I '.git|node_modules|bower_components' --dirsfirst "$@" | less -FRNX
}
# Show basic information from Wikipedia on command-line topic
# Requires 'jq'. (Install with 'sudo apt-get install -y jq'.)
function wikip() {
LANG="en"
if [[ -z $1 ]]; then
echo -e "No argument specified.\nUsage: wikip TOPIC\n"
else
var=$(echo $* | sed 's/ /_/g') # Transforms 'One Time' to 'One_Time'
wiki_data=$(curl -s "https://"$LANG".m.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&titles="$var"&redirects" | jq '.query.pages | to_entries[0] | .value.extract')
data=$(echo $wiki_data | sed 's/\\\"/"/g') # Removes \" characters
if [[ $data = "null" ]]; then
echo "Nothing found. Check query/topic."
else
url="https://en.m.wikipedia.org/wiki/"$var
echo -e ${data:1:${#data}-2}"\n"
echo "See more on "$url
fi
fi
}
# Create 7z archive with some reasonable defaults
function 7za() {
7z a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on $@
}
# Clean file names using various rules
function clean_file_names() {
for i in "$@"
do
b=$(\
echo "$i" | \
sed \
-e 's%([^()]*)%%g' -e '# Remove all parentheses' \
-e's%[♪▶♫♥"»«"]\+%%g' -e '# Removes one or more of various unwanted characters' \
-e "s%[,']\+%%g" -e '# Remove commas and single quotes' \
-e "s%\.\+%.%g" -e '# convert multiple consecutive periods into single period' \
-e "s%[:»]\+%_%g" -e '# convert multiple these unwanted characters into single _' \
-e "s%&%_and_%g" -e '# convert ampersand ("&") to "_and_"' \
-e's%^[-_\. ]\+%%' -e '# Remove dashes, periods, and spaces at beginning' \
-e's%-\+%-%g' -e '# convert multiple consecutive dashes into one dash' \
-e's%_\{2,99\}%__%g' -e '# convert multiple underscores to one __.' \
-e's%\(_-\)\+_%_-_%g' -e '# convert multiple _-_-_ to one __' \
-e's% \+% %g' -e '# convert multiple spaces to one space' \
-e's% - YouTube%%g' \
-e's%[-_ ]\+\(\.[^\.]\+\)$%\1%g' -e'# Remove spaces, periods, dashes, etc. before suffix/extension' \
-e's%[-_\. ]\+$%%' -e'# Remove dashes, periods, or whitespace at end (after extension)' \
)
c=$( echo "$i" | sed -e's%"%\\"%g')
[ "$i" != "$b" ] && echo "mv -v -- \"$c\" \"$b\""
done
}
function sysinfo() {
IFS=" " read LOAD1 LOAD5 LOAD15 <<<$(cat /proc/loadavg | awk '{ print $1,$2,$3 }')
# get free memory
IFS=" " read USED AVAIL TOTAL <<<$(free -htm | grep "Mem" | awk {'print $3,$7,$2'})
# get processes
PROCESS=`ps -eo user=|sort|uniq -c | awk '{ print $2 " " $1 }'`
PROCESS_ALL=`echo "$PROCESS"| awk {'print $2'} | awk '{ SUM += $1} END { print SUM }'`
PROCESS_ROOT=`echo "$PROCESS"| grep root | awk {'print $2'}`
PROCESS_USER=`echo "$PROCESS"| grep -v root | awk {'print $2'} | awk '{ SUM += $1} END { print SUM }'`
# get processors
PROCESSOR_NAME=`grep "model name" /proc/cpuinfo | cut -d ' ' -f3- | awk {'print $0'} | head -1`
PROCESSOR_COUNT=`grep -ioP 'processor\t:' /proc/cpuinfo | wc -l`
W="\e[0;39m"
G="\e[1;32m"
temp=""
if [ -x "$(command -v landscape-sysinfo)" ]; then
temp=$(landscape-sysinfo --sysinfo-plugins Temperature | sed 's/ *$//g' | sed 's/Temperature: //g')
fi
echo -e "
${W}system info:
$W Distro : $W`cat /etc/*release | grep "PRETTY_NAME" | cut -d "=" -f 2- | sed 's/"//g'`
$W Kernel : $W`uname -sr`
$W Uptime : $W`uptime -p`
$W Load : $G$LOAD1$W (1m), $G$LOAD5$W (5m), $G$LOAD15$W (15m)
$W Processes :$W $G$PROCESS_ROOT$W (root), $G$PROCESS_USER$W (user), $G$PROCESS_ALL$W (total)
$W CPU : $W$PROCESSOR_NAME ($G$PROCESSOR_COUNT$W vCPU)
$W Memory : $G$USED$W used, $G$AVAIL$W avail, $G$TOTAL$W total$W"
temp=""
if [ -x "$(command -v landscape-sysinfo)" ]; then
temp=$(landscape-sysinfo --sysinfo-plugins Temperature | sed 's/Temperature: //g' | sed 's/^ *//g')
fi
if [ -z "$temp" ]; then
echo -e "$W Temperature : $W$G$temp$W"
fi
}
# Convert datetime to Unix epoch timestamp
# Examples:
# $ date2epoch "2021-03-01 00:00:00+0600"
# 1614535200
#
# $ date2epoch # Shows current time
# 1640213943
# https://github.com/thombashi/dotfiles/blob/master/.functions.sh
date2epoch() {
if [ "$1" != "" ]; then
\date +%s -d "$1"
else
\date +%s
fi
}
# Convert Unix epoch timestamp to datetime
# Example:
# $ epoch2date 1234567890
# 2009-02-13 17:31:30-06:00
#
# https://github.com/thombashi/dotfiles/blob/master/.functions.sh
epoch2date() {
if [ "$1" == "" ]; then
echo "Usage: ${FUNCNAME[0]} EPOCH_TIME" 1>&2
return 22
fi
\date -d @"$1" --rfc-3339=seconds
}
# Create and attach to new tmux session with specified parameters.
# Defaults to session named "new" in ${HOME} directory with window
# named "main".
#
# https://tech.serhatteker.com/post/2022-02/tmux-new-session/
#
# Usage:
# $ tnew
# $ tnew remote ~/path/to/dir
# $ tnew remote ~/path/to/dir window_name
tnew() {
local session_name="${1:-new}"
local session_dir=${2:-~/}
local session_window_name="${3:-main}"
tmux new-session \
-d \
-s ${session_name} \
-c ${session_dir} \
-n ${session_window_name}
}
# Some convenient 'ls' aliases
# detailed list in alphabetical order
alias lss='ls --group-directories-first --color=always --time-style=+"%Y-%m-%d %I:%M:%S %p" -lhF'
# detailed list in reverse time order
alias ltr='ls --group-directories-first --color=always --time-style=+"%Y-%m-%d %I:%M:%S %p" -lhFtr'
# simple list in reverse time order
alias 1tr='ls --group-directories-first --color=always -1Ftr'
# just filenames in alphabetical order
alias lsf='ls --group-directories-first --color=always -F'
# Add an "alert" alias for long-running command.
# Usage: sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
# Get IPv4 address of specified interface (e.g., "eth0").
ipv4_addr() {
ip addr show $1 | grep 'inet ' | awk '{ print $2; }' | sed 's/\/.*$//'
}